feat(workflow): example covers security, platform, enterprise and resilience features
105 route tests, matrix crawl, spec and README updated. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -31,7 +31,7 @@ make test # whole repo
|
||||
make -f example/example.mk example-test # this part only, standalone
|
||||
```
|
||||
|
||||
Expected: `example suite: 37 passed, 0 failed`. Failure action: reproduce
|
||||
Expected: `example suite: 105 passed, 0 failed`. Failure action: reproduce
|
||||
through the real stack first (failing route-level test), then fix; the
|
||||
reproduction stays in the suite. Conventions: `tests/README.md`.
|
||||
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
# MoloApp
|
||||
|
||||
Native C++23 web framework: HTTP/1.1 + HTTP/2 runtime, routing, views,
|
||||
validation, templates, ORM (SQLite + Postgres), sessions, realtime,
|
||||
supervisor, clients, observability, multi-tenancy, audit, governance. One
|
||||
third-party dependency planned for TLS (wolfSSL). One CLI binary: `molo`.
|
||||
|
||||
This README states what works today. Gaps are listed at the bottom and in
|
||||
the spec next to the code that will close them. Where README and a spec
|
||||
disagree, the spec wins: `plan.md`, `plans/`, `src/*/SPEC.md`, `reverse.md`,
|
||||
`example/SPEC.md`.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Linux, `g++` 15+ with `-std=c++23`, GNU or BSD `make`
|
||||
- `libsqlite3` and `libpq` (the CLI links `-lsqlite3 -l:libpq.so.5`)
|
||||
- Optional: Postgres 18 for the postgres backend (`docker compose up -d postgres`)
|
||||
|
||||
```sh
|
||||
g++ --version && make --version
|
||||
```
|
||||
|
||||
## Build and test
|
||||
|
||||
```sh
|
||||
make # everything: libs, tests, build/molo
|
||||
make test # whole suite, every part
|
||||
make lint # warning-free build plus em dash ban
|
||||
make clean # rm -rf build
|
||||
```
|
||||
|
||||
Everything lands under `build/`. Warnings are errors in spirit: fix the
|
||||
cause, never silence them. `make deploy` is referenced in `AGENTS.md` but
|
||||
is not defined in the Makefile yet.
|
||||
|
||||
## The living example
|
||||
|
||||
A route-level demo of every feature, with 105 integration tests on the real
|
||||
stack (no mocks). Standalone, no other part needed.
|
||||
|
||||
```sh
|
||||
make -f example/example.mk example # build
|
||||
./build/example/living-server 8080 # run
|
||||
make -f example/example.mk example-test # expect: 105 passed, 0 failed
|
||||
```
|
||||
|
||||
Open `http://127.0.0.1:8080/` and click through the matrix. Narrow the
|
||||
window to 360px: the nav collapses into a dropdown. Quick probe:
|
||||
|
||||
```sh
|
||||
curl localhost:8080/health # {"status":"ok","tls":"stub-no-wolfssl"}
|
||||
```
|
||||
|
||||
Open `/stats` for live Chart.js charts of requests, latency, bytes and
|
||||
connections (Chart.js is embedded into the binary at build time). The
|
||||
feature -> route -> test -> plan matrix lives in `example/README.md`.
|
||||
Test conventions (one test file per URL, Arrange/Act/Assert, integration
|
||||
only) are in `tests/README.md`.
|
||||
|
||||
### How an app is written
|
||||
|
||||
`example/app/App.cpp` is the reference: an `Application`, middleware slots,
|
||||
and `Router`s mounted with a prefix. Apps chain, so mounting three apps
|
||||
under each other serves `/app1/app1/app1/...`.
|
||||
|
||||
```cpp
|
||||
auto app = std::make_shared<fw::Application>();
|
||||
app->use(fw::MiddlewareSlot::Errors, fw::errors_middleware());
|
||||
|
||||
fw::Router routing;
|
||||
register_routing_demo(routing, services);
|
||||
app->include_router("/routing", routing, "routing.");
|
||||
```
|
||||
|
||||
Note: `example/fw/` is a skeleton of the public API that the real parts
|
||||
under `src/` are being re-bound to, route by route. URLs and tests stay
|
||||
stable while that happens.
|
||||
|
||||
## The CLI: `molo`
|
||||
|
||||
Built by `make` to `build/molo`.
|
||||
|
||||
```sh
|
||||
./build/molo --help
|
||||
./build/molo help <command> # full help for one command
|
||||
```
|
||||
|
||||
Global flags: `--format json|text`, `-v` (repeat up to 3), `-q`, `-h`.
|
||||
Exit codes: `0` ok, `1` runtime, `2` usage, `69` unavailable. Stdout is the
|
||||
primary output only; logs go to stderr. `--format json` is always parseable.
|
||||
|
||||
| Command | What it does |
|
||||
|---|---|
|
||||
| `new <name> [--backend postgres\|sqlite] [--force]` | Scaffold a project (Makefile, AGENTS.md, `.env.json`, assets, templates, locales, `git init`). Refuses a non-empty dir without `--force`. |
|
||||
| `serve [--port N] [--reload] [--config F]` | Dev server. `--reload` watches and rebuilds; refused on prod config without `--allow-prod`. |
|
||||
| `build [--embed dir] [--out dir]` | Build, optionally embedding assets first. |
|
||||
| `embed <dir> --out f.cpp [--hpp f.hpp] [--namespace ns] [--gzip]` | Turn a static dir into constexpr C++ arrays. Output is byte-identical across runs. |
|
||||
| `migrate [--check \| --apply]` | Preview or apply database migrations. |
|
||||
| `health` | Local liveness and readiness summary. |
|
||||
| `supervisor start\|stop\|restart\|status\|logs` | Process supervisor. |
|
||||
| `task enqueue\|retry\|cancel\|inspect` | Background task queue (`--id` for inspect). |
|
||||
| `ai new\|continue` | The AI agent, see below. |
|
||||
| `expose serve\|agent\|list\|stats\|expose-key` | Reverse tunnels, see below. |
|
||||
| `verify`, `supply-check`, `release` | Offline artifact verification, pin and advisory gate, ordered release gate. |
|
||||
| `rollout`, `rollback`, `experiment`, `debug` | Operability: deploys, chaos, debug helpers. |
|
||||
|
||||
Fixed health paths on a running server, no auth: `/healthz`, `/readyz`,
|
||||
`/startupz`, `/metrics` (Prometheus text 0.0.4).
|
||||
|
||||
Start a new app:
|
||||
|
||||
```sh
|
||||
./build/molo new shop --backend sqlite
|
||||
cd shop && ls -A # .env.json AGENTS.md Makefile assets locales src templates
|
||||
```
|
||||
|
||||
## The agent: `molo ai`
|
||||
|
||||
OpenAI-compatible vibe-coding harness that knows the framework's features
|
||||
and conventions. Streams by default.
|
||||
|
||||
```sh
|
||||
export DEVPLACE_API_KEY=... # env only, never a flag or a file
|
||||
./build/molo ai new --prompt "a todo app with sqlite and a json api"
|
||||
./build/molo ai continue --prompt "add login"
|
||||
```
|
||||
|
||||
- Defaults: base `https://devplace.net/openai/v1`, model `molodetz`;
|
||||
override with `--base-url` and `--model`.
|
||||
- Secrets are redacted before the prompt is built. If redaction fails, the
|
||||
run aborts.
|
||||
- Plan then apply: file writes are confirmed by a human.
|
||||
- Caps: 30 s connect, 300 s session, 8 MB transcript, 50 actions.
|
||||
|
||||
## Reverse tunnels: `molo expose`
|
||||
|
||||
Publish a local endpoint through a MoloApp server over one outbound
|
||||
connection. The spec is `reverse.md` (claims, keys, upstream tables,
|
||||
routing precedence, caps).
|
||||
|
||||
```sh
|
||||
molo expose serve --slug /hook1 --upstream http://127.0.0.1:3000 # server side
|
||||
molo expose agent --slug /hook1 --key <key> # exposer side
|
||||
molo expose list
|
||||
molo expose stats # or --format json
|
||||
molo expose expose-key rotate
|
||||
```
|
||||
|
||||
Stats are zero-cost on the hot path (atomics), flushed in one transaction to
|
||||
SQLite by default (`system.db`) or Postgres. Per method: count, kB up/down,
|
||||
windowed kB/s, average latency.
|
||||
|
||||
## Configuration
|
||||
|
||||
`.env.json` in the workdir is loaded automatically; environment variables
|
||||
override it.
|
||||
|
||||
```json
|
||||
{
|
||||
"DATABASE_URL": "sqlite://system.db",
|
||||
"STATS_FLUSH_SECS": "5"
|
||||
}
|
||||
```
|
||||
|
||||
| Key | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `DATABASE_URL` | `sqlite://system.db` | `sqlite://...` or a postgres URL |
|
||||
| `STATS_FLUSH_SECS` | `5` | Stats flush interval |
|
||||
| `DEVPLACE_API_KEY` | none | Env only. Required by `molo ai` |
|
||||
| `MOLO_EXPOSE_KEY` | none | Claim key for the expose agent |
|
||||
|
||||
Postgres for local tests: `docker compose up -d postgres` (user/password
|
||||
`molo`, db `molo_test`, bound to 127.0.0.1:5432).
|
||||
|
||||
## Repo map
|
||||
|
||||
```text
|
||||
src/runtime event loop, HTTP/1.1 + HTTP/2, compression, static
|
||||
src/observability logging, events, metrics, tracing (zero-cost when off)
|
||||
src/security auth, hashing, crypto, sessions, guards, uploads
|
||||
src/data ORM, drivers, KV, cache, pubsub
|
||||
src/app application, routers, views, forms, validation, templates
|
||||
src/realtime WebSocket, SSE, Socket.IO, streaming, WebDAV, expose tunnels
|
||||
src/supervisor process supervisor, tasks, replication
|
||||
src/clients HTTP/REST client, OpenAPI, test double
|
||||
src/cli molo binary: CLI, dev server, embedder, AI, ops, i18n, CSP
|
||||
src/tenancy multi-tenancy
|
||||
src/audit hash-chained audit log, GDPR export/erasure, retention
|
||||
src/governance API keys, versioning, OpenAPI diff gate, surface linter
|
||||
src/operability deploys, drains, locks, breakers, SLO, chaos
|
||||
src/supplychain SBOM, provenance, pin policy, release attestation
|
||||
example/ living example (skeleton fw + demo routes)
|
||||
tests/ integration tests, mirrors URLs
|
||||
plans/ 15 detailed plans, index in plans/README.md
|
||||
```
|
||||
|
||||
Each part ships a `<part>.mk` fragment that the root Makefile includes, and
|
||||
most ship a `SPEC.md`. Every knob has a hard static cap, declared in that
|
||||
part's `caps` header (CLI: `src/cli/caps.hpp`).
|
||||
|
||||
## Working with agents on this repo
|
||||
|
||||
`AGENTS.md` is the entry point for autonomous work. Pipeline order:
|
||||
lint, suite, bump, changelog, commit, tag, deploy, verify. Commits are
|
||||
`<type>[(scope)][!]: <description>` (subject max 100 chars). Versions are
|
||||
derived from commits, never hand-chosen. Never cross alone: `specs/`,
|
||||
`CHANGELOG.md`, `VERSION`, tags, history rewrite, force push.
|
||||
|
||||
## Known gaps
|
||||
|
||||
Measured on this checkout, not aspirational:
|
||||
|
||||
- `molo serve` parks the loop; full HTTP serving waits on runtime lifecycle
|
||||
wiring (`src/cli/dev/dev_server.cpp`).
|
||||
- `molo ai continue` resumes within one process only; no durable session
|
||||
store (`src/cli/cli/cli_app.cpp`). HTTPS transport for the agent is a stub
|
||||
until wolfSSL lands.
|
||||
- TLS is a stub everywhere (`/health` reports `stub-no-wolfssl`).
|
||||
- `molo expose <upstream> key@server /claim` shorthand from `reverse.md` is
|
||||
not wired; use the `serve` and `agent` subcommands with flags.
|
||||
- `example/fw/` is a skeleton, not the real framework; the swap to `src/`
|
||||
namespaces is incremental.
|
||||
- No root `deploy` target, no `CHANGELOG.md` or `VERSION` yet.
|
||||
- No benchmark numbers are published. Any performance claim without a
|
||||
measurement behind it is not a claim.
|
||||
+85
-2
@@ -10,10 +10,11 @@ make -f example/example.mk example
|
||||
./build/example/living-server 8080
|
||||
```
|
||||
|
||||
Open `http://127.0.0.1:8080/` and click through the matrix. Narrow the
|
||||
Open `http://127.0.0.1:8080/` and click through the matrix; `/stats` has the
|
||||
charts (Chart.js is embedded in the binary, no CDN). Narrow the
|
||||
window to 360px: the top nav collapses into a dropdown menu.
|
||||
|
||||
Run the suite (37 route-level integration tests, real stack, no mocks):
|
||||
Run the suite (105 route-level integration tests, real stack, no mocks):
|
||||
|
||||
```sh
|
||||
make -f example/example.mk example-test
|
||||
@@ -78,6 +79,86 @@ on a missing row.
|
||||
| workflow | `/workflow/release` | `tests/example/workflow/release_test.cpp` | `plans/10-workflow-example.md` 6.2 |
|
||||
| redirects | `/redirect/here` | `tests/example/redirect/here_test.cpp` | `plans/05-request-routing.md` |
|
||||
|
||||
| statistics | `/stats` | `tests/example/stats/page_test.cpp` | `plans/02-observability.md` |
|
||||
| statistics data | `/stats/data` | `tests/example/stats/data_test.cpp` | `plans/02-observability.md` |
|
||||
|
||||
### Extended features
|
||||
|
||||
Added in the second pass: security, platform, enterprise, resilience and
|
||||
data-depth demos. Each row is a plain GET that answers 2xx; actions are
|
||||
buttons or forms on the page. Per-module gaps versus `src/` are in the
|
||||
header of `example/fw/{SecurityExtra,Platform,Enterprise,Resilience}.hpp`.
|
||||
`tests/example/matrix_test.cpp` crawls every row of the index.
|
||||
|
||||
| Feature | Route | Test file |
|
||||
|---|---|---|
|
||||
| CSRF token form | `/security/csrf` | `tests/example/security/csrf_test.cpp` |
|
||||
| CORS preflight allowlist | `/security/cors` | `tests/example/security/cors_test.cpp` |
|
||||
| Rate limiter (429 + Retry-After) | `/security/rate` | `tests/example/security/rate_test.cpp` |
|
||||
| Security headers | `/security/headers` | `tests/example/security/headers_test.cpp` |
|
||||
| CSP nonce page | `/csp/page` | `tests/example/csp/page_test.cpp` |
|
||||
| CSP report endpoint | `/csp/report` | `tests/example/csp/report_test.cpp` |
|
||||
| SHA-256 and HMAC | `/crypto/hash` | `tests/example/crypto/hash_test.cpp` |
|
||||
| Secure random token | `/crypto/random` | `tests/example/crypto/random_test.cpp` |
|
||||
| Password hashing (demo) | `/crypto/password` | `tests/example/crypto/password_test.cpp` |
|
||||
| Roles and permissions | `/security/roles` | `tests/example/security/` |
|
||||
| Secrets provider (masked) | `/security/secrets` | `tests/example/security/secrets_test.cpp` |
|
||||
| Upload validation | `/security/upload` | `tests/example/security/upload_test.cpp` |
|
||||
| SQL and path guard | `/security/guard` | `tests/example/security/guard_test.cpp` |
|
||||
| Denial sink | `/security/denials` | `tests/example/security/denials_test.cpp` |
|
||||
| Login form with session cookie | `/security/login` | `tests/example/security/login_test.cpp` |
|
||||
| i18n | `/i18n` | `tests/example/i18n/` |
|
||||
| gzip compression | `/compress/demo` | `tests/example/compress/demo_test.cpp` |
|
||||
| conditional GET and ranges | `/conditional/doc` | `tests/example/conditional/doc_test.cpp` |
|
||||
| liveness probe | `/healthz` | `tests/example/healthz/` |
|
||||
| readiness probe | `/readyz` | `tests/example/readyz/` |
|
||||
| startup gate | `/startupz` | `tests/example/startupz/` |
|
||||
| prometheus metrics | `/metrics` | `tests/example/metrics/` |
|
||||
| structured logging | `/logging/records` | `tests/example/logging/records_test.cpp` |
|
||||
| trace context | `/context/trace` | `tests/example/context/trace_test.cpp` |
|
||||
| DI container | `/di/services` | `tests/example/di/services_test.cpp` |
|
||||
| flash messages | `/flash` | `tests/example/flash/` |
|
||||
| middleware builtins | `/middleware/demo` | `tests/example/middleware/demo_test.cpp` |
|
||||
| expose stats | `/expose/stats` | `tests/example/expose/stats_test.cpp` |
|
||||
| CLI commands | `/cli/commands` | `tests/example/cli/commands_test.cpp` |
|
||||
| Tenant resolution (header, subdomain, path) | `/tenancy/resolve` | `tests/example/tenancy/resolve_test.cpp` |
|
||||
| Tenant path resolution | `/tenancy/t/demo/whoami` | `tests/example/tenancy/` |
|
||||
| Tenant data isolation | `/tenancy/data` | `tests/example/tenancy/data_test.cpp` |
|
||||
| Tenant quotas | `/tenancy/quota` | `tests/example/tenancy/quota_test.cpp` |
|
||||
| Tenant feature flags | `/tenancy/flags` | `tests/example/tenancy/flags_test.cpp` |
|
||||
| Tenant config overlay | `/tenancy/config` | `tests/example/tenancy/config_test.cpp` |
|
||||
| Per-tenant metrics | `/tenancy/metrics` | `tests/example/tenancy/metrics_test.cpp` |
|
||||
| Tenant provisioning form | `/tenancy/provision` | `tests/example/tenancy/provision_test.cpp` |
|
||||
| Hash-chained audit log | `/audit/log` | `tests/example/audit/log_test.cpp` |
|
||||
| Audit tamper detection | `/audit/verify` | `tests/example/audit/verify_test.cpp` |
|
||||
| PII masking and redaction | `/audit/mask` | `tests/example/audit/mask_test.cpp` |
|
||||
| Retention and legal hold | `/audit/retention` | `tests/example/audit/retention_test.cpp` |
|
||||
| Data subject export and erasure | `/audit/subject` | `tests/example/audit/subject_test.cpp` |
|
||||
| API keys with scopes | `/governance/keys` | `tests/example/governance/keys_test.cpp` |
|
||||
| Tiers and rate limit headers | `/governance/tiers` | `tests/example/governance/tiers_test.cpp` |
|
||||
| API versions (Deprecation, Sunset) | `/v1/items` | `tests/example/v1/items_test.cpp` |
|
||||
| API version list | `/governance/versions` | `tests/example/governance/versions_test.cpp` |
|
||||
| Route linter | `/governance/lint` | `tests/example/governance/lint_test.cpp` |
|
||||
| OpenAPI spec differ | `/governance/diff` | `tests/example/governance/diff_test.cpp` |
|
||||
| RFC 7807 problem+json | `/governance/problem` | `tests/example/governance/problem_test.cpp` |
|
||||
| Circuit breaker | `/operability/breaker` | `tests/example/operability/breaker_test.cpp` |
|
||||
| Bulkhead | `/operability/bulkhead` | `tests/example/operability/bulkhead_test.cpp` |
|
||||
| Load shedder | `/operability/shedder` | `tests/example/operability/shedder_test.cpp` |
|
||||
| Deadline propagation | `/operability/deadline` | `tests/example/operability/deadline_test.cpp` |
|
||||
| SLO error budget | `/operability/slo` | `tests/example/operability/slo_test.cpp` |
|
||||
| Chaos experiment | `/operability/chaos` | `tests/example/operability/chaos_test.cpp` |
|
||||
| Deploy strategies | `/operability/deploy` | `tests/example/operability/deploy_test.cpp` |
|
||||
| Lease, election, fenced lock | `/operability/coord` | `tests/example/operability/coord_test.cpp` |
|
||||
| Supply chain gate | `/supplychain` | `tests/example/supplychain/` |
|
||||
| Client retry and backoff | `/clients/retry` | `tests/example/clients/retry_test.cpp` |
|
||||
| Client session: cookies, pool, proxy, auth | `/clients/session` | `tests/example/clients/session_test.cpp` |
|
||||
| Migrations: check then apply | `/data/migrations` | `tests/example/data/migrations_test.cpp` |
|
||||
| Transaction rollback | `/data/transaction` | `tests/example/data/transaction_test.cpp` |
|
||||
| Query builder and relations | `/data/query` | `tests/example/data/query_test.cpp` |
|
||||
| Singleflight | `/data/singleflight` | `tests/example/data/singleflight_test.cpp` |
|
||||
| TTL store, LRU, pubsub | `/data/ttl` | `tests/example/data/ttl_test.cpp` |
|
||||
| Debug snapshot | `/operability/debug` | `tests/example/operability/debug_test.cpp` |
|
||||
|
||||
## Layout
|
||||
|
||||
```text
|
||||
@@ -89,5 +170,7 @@ example/
|
||||
fw/ # skeletal framework public API (namespace molo::example::fw)
|
||||
app/ # demo routes (namespace molo::example::app)
|
||||
static/ # disk static assets (responsive CSS, tiny JS)
|
||||
assets/ # embedded at build time (Chart.js, stats.js) via src/cli/embed
|
||||
tools/ # build helper wrapping the embedder
|
||||
tests/example/ # route-level integration tests mirroring URLs
|
||||
```
|
||||
|
||||
+32
-1
@@ -19,6 +19,31 @@ owning sibling plan and the file that will close it.
|
||||
9. The release demo parses Conventional Commits, maps the bump, renders a
|
||||
changelog entry, and gates on checks (dry-run: never writes).
|
||||
10. All pages render on a 360px viewport; wide nav collapses to a dropdown.
|
||||
11. Browser form posts that fail validation answer 422 with the same form:
|
||||
a summary box (count, one link per failing field) and the message next
|
||||
to each invalid input, entered values kept. Never raw JSON in a page.
|
||||
JSON clients (Accept or Content-Type `application/json`) keep the
|
||||
`validation_error` body. One partial (`form_page.html`) and one helper
|
||||
(`app/FormUi.hpp`) serve every form.
|
||||
12. `GET /stats` renders Chart.js charts from `GET /stats/data`: requests,
|
||||
errors, latency avg/p50/p95/p99 and histogram, bytes in/out, status
|
||||
codes, methods, top routes, connections (total, active, peak, timeouts,
|
||||
malformed, cap left), plus service state (stores, cache hit/miss, tasks,
|
||||
workers, ORM, metrics registry). History: 90 ten-second buckets.
|
||||
13. Chart.js 4.4.7 and the page script are embedded at build time:
|
||||
`example/assets` -> `build/example/gen/assets.{cpp,hpp}` through the
|
||||
MoloApp embedder (`src/cli/embed`), served at `/embedded/{name}`.
|
||||
14. Every matrix row answers a plain GET with 2xx/3xx (401 for `/auth/me`
|
||||
by design). `tests/example/matrix_test.cpp` crawls them all.
|
||||
15. Feature groups added: security extras (csrf, cors, rate limit, headers,
|
||||
csp, crypto, roles, secrets, upload, guards, denials, login), platform
|
||||
(i18n, compression, conditional GET and ranges, probes, prometheus,
|
||||
logging, trace context, DI, flash, middleware, expose stats, CLI
|
||||
reference), enterprise (tenancy, audit, governance), resilience (breaker,
|
||||
bulkhead, shedder, deadline, slo, chaos, deploy, coord, debug, supply
|
||||
chain, client retry and session, migrations, transactions, query
|
||||
builder, singleflight, ttl store). Each is a skeleton of the real `src/`
|
||||
module; per-module gaps are in the header of its `fw/` file.
|
||||
|
||||
## Caps
|
||||
|
||||
@@ -51,7 +76,8 @@ auth, 403 bad credentials, 404 unknown, 405 wrong method, 406 no format,
|
||||
|
||||
## Isolation
|
||||
|
||||
May depend on: C++23 stdlib, POSIX sockets, `example/fw/` only. May NOT
|
||||
May depend on: C++23 stdlib, POSIX sockets, `example/fw/` only. Build-time
|
||||
only: the embedder sources in `src/cli/embed` (asset embedding). May NOT
|
||||
depend on: any `src/` tree (does not exist yet in this worktree), wolfSSL
|
||||
(stub behind `ITlsContext`), real Postgres/SQLite (in-memory doubles),
|
||||
real network except loopback. Namespaces mirror directories:
|
||||
@@ -72,6 +98,11 @@ real network except loopback. Namespaces mirror directories:
|
||||
- Full validation coercions, template sandbox, DI container, flash
|
||||
messages: owner 05-request-routing.md, files `example/fw/Validate.*`,
|
||||
`example/fw/Templates.*`, `example/app/App.*`.
|
||||
- Server accepts sequentially and stops after 512 connections (cap above);
|
||||
the stats page shows connections left. Owner: 01-runtime.md,
|
||||
`example/fw/Server.*`.
|
||||
- Template engine has no `elif`, `not`, or macros. Owner:
|
||||
05-request-routing.md, `example/fw/Templates.*`.
|
||||
- Real WS/Socket.IO/SSE framing, rooms, namespaces, realtime clients:
|
||||
owner 06-realtime.md, file `example/app/RealtimeDemo.*`.
|
||||
- Worker processes, durable streams, conflict hooks, multi-instance:
|
||||
|
||||
@@ -51,6 +51,22 @@ std::shared_ptr<fw::Application> build_application(Services& services) {
|
||||
register_stats_demo(stats, services);
|
||||
app->include_router("", stats);
|
||||
|
||||
fw::Router security_extra;
|
||||
register_security_extra_demo(security_extra, services);
|
||||
app->include_router("", security_extra);
|
||||
|
||||
fw::Router platform;
|
||||
register_platform_demo(platform, services);
|
||||
app->include_router("", platform);
|
||||
|
||||
fw::Router enterprise;
|
||||
register_enterprise_demo(enterprise, services);
|
||||
app->include_router("", enterprise);
|
||||
|
||||
fw::Router resilience;
|
||||
register_resilience_demo(resilience, services);
|
||||
app->include_router("", resilience);
|
||||
|
||||
register_chain_demo(app, services);
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../fw/App.hpp"
|
||||
#include "../fw/Data.hpp"
|
||||
@@ -47,6 +49,12 @@ struct Services {
|
||||
std::shared_ptr<fw::OpenApi> openapi = std::make_shared<fw::OpenApi>();
|
||||
std::shared_ptr<fw::Environment> templates =
|
||||
std::make_shared<fw::Environment>();
|
||||
// Feature matrix rows (feature, route) shown on the index page. Each
|
||||
// register_*_demo adds its own rows with add_feature().
|
||||
std::vector<std::pair<std::string, std::string>> features;
|
||||
void add_feature(std::string feature, std::string route) {
|
||||
features.emplace_back(std::move(feature), std::move(route));
|
||||
}
|
||||
std::map<std::string, std::string> embedded;
|
||||
std::string static_root = "example/static";
|
||||
std::string cookie_secret = "living-example-secret";
|
||||
@@ -64,6 +72,10 @@ void register_formats_demo(fw::Router& router, Services& services);
|
||||
void register_realtime_demo(fw::Router& router, Services& services);
|
||||
void register_ops_demo(fw::Router& router, Services& services);
|
||||
void register_stats_demo(fw::Router& router, Services& services);
|
||||
void register_security_extra_demo(fw::Router& router, Services& services);
|
||||
void register_platform_demo(fw::Router& router, Services& services);
|
||||
void register_enterprise_demo(fw::Router& router, Services& services);
|
||||
void register_resilience_demo(fw::Router& router, Services& services);
|
||||
|
||||
void load_templates(Services& services);
|
||||
void load_embedded(Services& services);
|
||||
|
||||
@@ -72,7 +72,10 @@ void register_data_demo(fw::Router& router, Services& services) {
|
||||
|
||||
router.get("/kv/items", "kv-get", [kv](fw::Request req) {
|
||||
std::string key = req.query_or("key", "");
|
||||
if (key.empty()) return fw::JsonResponse("{\"error\":\"key required\"}", 400);
|
||||
if (key.empty())
|
||||
return fw::JsonResponse("{\"entries\":" + std::to_string(kv->size()) +
|
||||
",\"usage\":\"GET ?key=<key>, POST key+value\"}",
|
||||
200);
|
||||
std::string value;
|
||||
if (!kv->get(key, value))
|
||||
return fw::JsonResponse("{\"error\":\"not found\"}", 404);
|
||||
|
||||
@@ -0,0 +1,691 @@
|
||||
#include "App.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
|
||||
#include "FormUi.hpp"
|
||||
#include "../fw/Enterprise.hpp"
|
||||
#include "../fw/Router.hpp"
|
||||
#include "../fw/Templates.hpp"
|
||||
#include "../fw/Validate.hpp"
|
||||
|
||||
namespace molo::example::app {
|
||||
|
||||
namespace {
|
||||
|
||||
using fw::Response;
|
||||
using fw::Request;
|
||||
|
||||
// All enterprise demo state lives here, owned through one shared_ptr.
|
||||
struct Hub {
|
||||
fw::TenantResolver resolver;
|
||||
fw::TenantCatalog catalog;
|
||||
fw::TenantData data;
|
||||
fw::TenantQuota quota;
|
||||
fw::FeatureFlags flags;
|
||||
fw::ConfigOverlay config;
|
||||
fw::TenantMetrics metrics;
|
||||
fw::AuditChain chain;
|
||||
fw::RetentionStore retention;
|
||||
fw::SubjectStore subjects;
|
||||
fw::ApiKeyStore keys;
|
||||
fw::QuotaLedger ledger;
|
||||
fw::VersionTable versions;
|
||||
Hub() {
|
||||
chain.append("system", "boot", "audit", "chain started");
|
||||
chain.append("ada", "login", "session", "from [IP]");
|
||||
chain.append("bob", "export", "report", "monthly report");
|
||||
}
|
||||
};
|
||||
using HubPtr = std::shared_ptr<Hub>;
|
||||
|
||||
std::string q(const std::string& s) { return "\"" + fw::json_escape(s) + "\""; }
|
||||
|
||||
std::map<std::string, std::string> input(const Request& req) {
|
||||
auto in = fw::parse_json_object_flat(req.body);
|
||||
if (in.empty()) in = fw::parse_form(req.body);
|
||||
return in;
|
||||
}
|
||||
|
||||
std::string get_or(const std::map<std::string, std::string>& m, const std::string& k,
|
||||
const std::string& d = "") {
|
||||
auto it = m.find(k);
|
||||
return it == m.end() ? d : it->second;
|
||||
}
|
||||
|
||||
bool json_client(const Request& req) { return !wants_html(req); }
|
||||
|
||||
Response page(fw::Environment* env, const std::string& heading, const std::string& body,
|
||||
int status = 200) {
|
||||
fw::TemplateCtx c;
|
||||
c["title"] = heading;
|
||||
c["heading"] = heading;
|
||||
c["body"] = body;
|
||||
return Response(status, env->render("ent_page.html", c), "text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
Response form_page(fw::Environment* env, FormView& v, int status = 200) {
|
||||
return Response(status, env->render("form_page.html", v.ctx()), "text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
Response form_fail(fw::Environment* env, const Request& req, FormView& v,
|
||||
const fw::ValidationError& e,
|
||||
const std::map<std::string, std::string>& in) {
|
||||
if (json_client(req)) return fw::JsonResponse(e.to_json(), 422);
|
||||
v.values = in;
|
||||
v.error = &e;
|
||||
return form_page(env, v, 422);
|
||||
}
|
||||
|
||||
Response form_ok(fw::Environment* env, const Request& req, FormView& v,
|
||||
const std::string& notice, const std::string& json, int status = 200) {
|
||||
if (json_client(req)) return fw::JsonResponse(json, status);
|
||||
v.notice = notice;
|
||||
v.done = true;
|
||||
return form_page(env, v, status);
|
||||
}
|
||||
|
||||
std::string table(const std::vector<std::string>& head,
|
||||
const std::vector<std::vector<std::string>>& rows) {
|
||||
std::string t = "<div class=\"scroll\"><table><thead><tr>";
|
||||
for (const auto& h : head) t += "<th>" + fw::html_escape(h) + "</th>";
|
||||
t += "</tr></thead><tbody>";
|
||||
for (const auto& r : rows) {
|
||||
t += "<tr>";
|
||||
for (const auto& c : r) t += "<td>" + fw::html_escape(c) + "</td>";
|
||||
t += "</tr>";
|
||||
}
|
||||
return t + "</tbody></table></div>";
|
||||
}
|
||||
|
||||
std::string form_html(const std::string& action, const std::string& label,
|
||||
const std::vector<std::pair<std::string, std::string>>& fields,
|
||||
const std::string& button) {
|
||||
std::string f = "<form method=\"post\" action=\"" + action + "\"><h2>" +
|
||||
fw::html_escape(label) + "</h2>";
|
||||
for (const auto& [name, lab] : fields)
|
||||
f += "<div class=\"field\"><label for=\"" + name + "\">" + fw::html_escape(lab) +
|
||||
"</label><input id=\"" + name + "\" name=\"" + name + "\"></div>";
|
||||
return f + "<button type=\"submit\">" + button + "</button></form>";
|
||||
}
|
||||
|
||||
// ---- tenancy ---------------------------------------------------------------
|
||||
struct Tctx {
|
||||
fw::TenantRef ref;
|
||||
const fw::Tenant* tenant = nullptr;
|
||||
std::optional<Response> failure;
|
||||
};
|
||||
|
||||
Tctx tenant_of(const Hub& h, const Request& req, const std::string& path_tenant = "") {
|
||||
Tctx c;
|
||||
c.ref = h.resolver.resolve(req, path_tenant);
|
||||
if (!c.ref.error.empty()) {
|
||||
c.failure = fw::problem_response(400, "Bad tenant id", c.ref.error, req.path);
|
||||
return c;
|
||||
}
|
||||
c.tenant = h.catalog.find(c.ref.id);
|
||||
if (!c.tenant)
|
||||
c.failure = fw::problem_response(404, "Unknown tenant", "no tenant " + c.ref.id, req.path);
|
||||
return c;
|
||||
}
|
||||
|
||||
std::string tenant_json(const Tctx& c) {
|
||||
return "{\"tenant\":" + q(c.ref.id) + ",\"source\":" + q(c.ref.source) +
|
||||
",\"plan\":" + q(c.tenant ? c.tenant->plan : "") + "}";
|
||||
}
|
||||
|
||||
void register_tenancy(fw::Router& router, Services& services, const HubPtr& hub,
|
||||
fw::Environment* env) {
|
||||
router.get("/tenancy/resolve", "tenancy-resolve", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
hub->metrics.inc(c.ref.id, "resolve");
|
||||
return fw::JsonResponse(tenant_json(c));
|
||||
});
|
||||
router.get("/tenancy/t/{tenant}/whoami", "tenancy-path", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req, req.param_or("tenant", ""));
|
||||
if (c.failure) return *c.failure;
|
||||
hub->metrics.inc(c.ref.id, "whoami");
|
||||
return fw::JsonResponse(tenant_json(c));
|
||||
});
|
||||
|
||||
router.get("/tenancy/data", "tenancy-data", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
hub->metrics.inc(c.ref.id, "data.list");
|
||||
std::string items;
|
||||
for (const auto& i : hub->data.list(c.ref.id)) items += (items.empty() ? "" : ",") + q(i);
|
||||
return fw::JsonResponse("{\"tenant\":" + q(c.ref.id) + ",\"items\":[" + items + "]}");
|
||||
});
|
||||
router.post("/tenancy/data", "tenancy-data-add", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
std::string item = get_or(input(req), "item");
|
||||
if (item.empty() || item.size() > 200)
|
||||
return fw::problem_response(422, "Invalid item", "item must be 1-200 chars", req.path);
|
||||
if (!hub->data.add(c.ref.id, item))
|
||||
return fw::problem_response(429, "Tenant data cap", "50 items per tenant", req.path);
|
||||
hub->metrics.inc(c.ref.id, "data.add");
|
||||
return fw::JsonResponse("{\"ok\":true,\"tenant\":" + q(c.ref.id) + "}", 201);
|
||||
});
|
||||
|
||||
auto quota_json = [hub](const Tctx& c) {
|
||||
return "{\"tenant\":" + q(c.ref.id) + ",\"plan\":" + q(c.tenant->plan) +
|
||||
",\"used\":" + std::to_string(hub->quota.used(c.ref.id)) +
|
||||
",\"limit\":" + std::to_string(fw::TenantQuota::limit_for(c.tenant->plan)) + "}";
|
||||
};
|
||||
router.get("/tenancy/quota", "tenancy-quota", [hub, quota_json](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
return fw::JsonResponse(quota_json(c));
|
||||
});
|
||||
router.post("/tenancy/quota", "tenancy-quota-use", [hub, quota_json](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
if (!hub->quota.consume(c.ref.id, c.tenant->plan)) {
|
||||
hub->metrics.inc(c.ref.id, "quota.denied");
|
||||
Response r = fw::problem_response(429, "Quota exceeded", quota_json(c), req.path);
|
||||
r.headers.set("Retry-After", "60");
|
||||
return r;
|
||||
}
|
||||
hub->metrics.inc(c.ref.id, "quota.used");
|
||||
return fw::JsonResponse(quota_json(c));
|
||||
});
|
||||
|
||||
router.get("/tenancy/flags", "tenancy-flags", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
std::string out;
|
||||
for (const auto& [f, on] : hub->flags.effective(c.ref.id))
|
||||
out += (out.empty() ? "" : ",") + q(f) + ":" + (on ? "true" : "false");
|
||||
return fw::JsonResponse("{\"tenant\":" + q(c.ref.id) + ",\"flags\":{" + out + "}}");
|
||||
});
|
||||
router.post("/tenancy/flags", "tenancy-flags-set", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
auto in = input(req);
|
||||
std::string flag = get_or(in, "flag"), on = get_or(in, "enabled");
|
||||
if (!hub->flags.known(flag))
|
||||
return fw::problem_response(422, "Unknown flag", "flag " + flag, req.path);
|
||||
if (on != "true" && on != "false")
|
||||
return fw::problem_response(422, "Invalid value", "enabled must be true or false", req.path);
|
||||
if (!hub->flags.set(c.ref.id, flag, on == "true"))
|
||||
return fw::problem_response(429, "Flag cap", "override cap reached", req.path);
|
||||
hub->metrics.inc(c.ref.id, "flags.set");
|
||||
return fw::JsonResponse("{\"ok\":true,\"flag\":" + q(flag) + ",\"enabled\":" + on + "}");
|
||||
});
|
||||
|
||||
router.get("/tenancy/config", "tenancy-config", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
std::string out;
|
||||
for (const auto& [k, v] : hub->config.effective(c.ref.id))
|
||||
out += (out.empty() ? "" : ",") + q(k) + ":" + q(v);
|
||||
return fw::JsonResponse("{\"tenant\":" + q(c.ref.id) + ",\"config\":{" + out + "}}");
|
||||
});
|
||||
router.post("/tenancy/config", "tenancy-config-set", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
auto in = input(req);
|
||||
std::string key = get_or(in, "key"), value = get_or(in, "value");
|
||||
if (!hub->config.known(key))
|
||||
return fw::problem_response(422, "Unknown key", "key " + key, req.path);
|
||||
if (value.empty() || value.size() > 64)
|
||||
return fw::problem_response(422, "Invalid value", "value must be 1-64 chars", req.path);
|
||||
if (!hub->config.set(c.ref.id, key, value))
|
||||
return fw::problem_response(429, "Config cap", "override cap reached", req.path);
|
||||
hub->metrics.inc(c.ref.id, "config.set");
|
||||
return fw::JsonResponse("{\"ok\":true}");
|
||||
});
|
||||
|
||||
router.get("/tenancy/metrics", "tenancy-metrics", [hub](Request req) -> Response {
|
||||
(void)req;
|
||||
std::string out;
|
||||
for (const auto& [t, m] : hub->metrics.all()) {
|
||||
std::string inner;
|
||||
for (const auto& [k, v] : m)
|
||||
inner += (inner.empty() ? "" : ",") + q(k) + ":" + std::to_string(v);
|
||||
out += (out.empty() ? "" : ",") + q(t) + ":{" + inner + "}";
|
||||
}
|
||||
return fw::JsonResponse("{\"tenants\":{" + out + "}}");
|
||||
});
|
||||
|
||||
auto prov_view = [] {
|
||||
FormView v;
|
||||
v.title = "Provision a tenant";
|
||||
v.action = "/tenancy/provision";
|
||||
v.submit = "Provision";
|
||||
v.fields = {{"id", "Tenant id", "text", "2-32 chars: a-z, 0-9, dash"},
|
||||
{"name", "Name", "text", ""},
|
||||
{"plan", "Plan", "text", "free or pro"}};
|
||||
return v;
|
||||
};
|
||||
router.get("/tenancy/provision", "tenancy-provision-form", [env, prov_view](Request) {
|
||||
FormView v = prov_view();
|
||||
return form_page(env, v);
|
||||
});
|
||||
router.post("/tenancy/provision", "tenancy-provision",
|
||||
[hub, env, prov_view](Request req) -> Response {
|
||||
FormView v = prov_view();
|
||||
auto in = input(req);
|
||||
fw::Model m({{"id", fw::FieldType::String, true, 2, 32, 0, 0, false, ""},
|
||||
{"name", fw::FieldType::String, true, 1, 80, 0, 0, false, ""},
|
||||
{"plan", fw::FieldType::String, false, 0, 8, 0, 0, false, "free"}});
|
||||
try {
|
||||
auto clean = m.validate(in);
|
||||
std::vector<fw::FieldError> bad;
|
||||
if (!fw::TenantResolver::valid_id(clean["id"]))
|
||||
bad.push_back({"id", "use a-z, 0-9 and dash only"});
|
||||
if (clean["plan"] != "free" && clean["plan"] != "pro")
|
||||
bad.push_back({"plan", "must be free or pro"});
|
||||
if (!bad.empty()) throw fw::ValidationError(bad);
|
||||
std::string why = hub->catalog.provision(clean["id"], clean["name"], clean["plan"]);
|
||||
if (!why.empty()) throw fw::ValidationError({{"id", why}});
|
||||
return form_ok(env, req, v, "Tenant " + clean["id"] + " provisioned.",
|
||||
"{\"ok\":true,\"tenant\":" + q(clean["id"]) + "}", 201);
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return form_fail(env, req, v, e, in);
|
||||
}
|
||||
});
|
||||
|
||||
services.add_feature("Tenant resolution (header, subdomain, path)", "/tenancy/resolve");
|
||||
services.add_feature("Tenant path resolution", "/tenancy/t/demo/whoami");
|
||||
services.add_feature("Tenant data isolation", "/tenancy/data");
|
||||
services.add_feature("Tenant quotas", "/tenancy/quota");
|
||||
services.add_feature("Tenant feature flags", "/tenancy/flags");
|
||||
services.add_feature("Tenant config overlay", "/tenancy/config");
|
||||
services.add_feature("Per-tenant metrics", "/tenancy/metrics");
|
||||
services.add_feature("Tenant provisioning form", "/tenancy/provision");
|
||||
}
|
||||
|
||||
// ---- audit -----------------------------------------------------------------
|
||||
std::string records_json(const fw::AuditChain& chain) {
|
||||
std::string out;
|
||||
for (const auto& r : chain.records())
|
||||
out += std::string(out.empty() ? "" : ",") + "{\"index\":" + std::to_string(r.index) +
|
||||
",\"actor\":" + q(r.actor) + ",\"action\":" + q(r.action) +
|
||||
",\"subject\":" + q(r.subject) + ",\"detail\":" + q(r.detail) +
|
||||
",\"hash\":" + q(r.hash) + "}";
|
||||
return out;
|
||||
}
|
||||
|
||||
void register_audit(fw::Router& router, Services& services, const HubPtr& hub,
|
||||
fw::Environment* env) {
|
||||
auto log_view = [] {
|
||||
FormView v;
|
||||
v.title = "Append audit record";
|
||||
v.action = "/audit/log";
|
||||
v.submit = "Append";
|
||||
v.fields = {{"actor", "Actor", "text", ""},
|
||||
{"action", "Action", "text", ""},
|
||||
{"subject", "Subject", "text", ""},
|
||||
{"detail", "Detail", "textarea", "PII is redacted before storage"}};
|
||||
return v;
|
||||
};
|
||||
|
||||
router.get("/audit/log", "audit-log", [hub, env](Request req) -> Response {
|
||||
if (json_client(req))
|
||||
return fw::JsonResponse("{\"records\":[" + records_json(hub->chain) + "]}");
|
||||
std::vector<std::vector<std::string>> rows;
|
||||
for (const auto& r : hub->chain.records())
|
||||
rows.push_back({std::to_string(r.index), r.actor, r.action, r.subject, r.detail,
|
||||
r.hash.substr(0, 12)});
|
||||
auto bad = hub->chain.verify();
|
||||
std::string status = bad ? "<p class=\"error\">Chain broken at index " +
|
||||
std::to_string(*bad) + "</p>"
|
||||
: "<p class=\"ok\">Chain intact (" +
|
||||
std::to_string(hub->chain.records().size()) + " records)</p>";
|
||||
return page(env, "Audit log",
|
||||
status + table({"#", "Actor", "Action", "Subject", "Detail", "Hash"}, rows) +
|
||||
form_html("/audit/log", "Append record",
|
||||
{{"actor", "Actor"}, {"action", "Action"},
|
||||
{"subject", "Subject"}, {"detail", "Detail"}},
|
||||
"Append") +
|
||||
"<p><a href=\"/audit/verify\">Verify</a></p>");
|
||||
});
|
||||
router.post("/audit/log", "audit-log-append", [hub, env, log_view](Request req) -> Response {
|
||||
FormView v = log_view();
|
||||
auto in = input(req);
|
||||
fw::Model m({{"actor", fw::FieldType::String, true, 1, 40, 0, 0, false, ""},
|
||||
{"action", fw::FieldType::String, true, 1, 40, 0, 0, false, ""},
|
||||
{"subject", fw::FieldType::String, true, 1, 80, 0, 0, false, ""},
|
||||
{"detail", fw::FieldType::String, false, 0, 500, 0, 0, false, ""}});
|
||||
try {
|
||||
auto c = m.validate(in);
|
||||
if (!hub->chain.append(c["actor"], c["action"], c["subject"],
|
||||
fw::PiiMasker::redact(c["detail"])))
|
||||
throw fw::ValidationError({{"actor", "audit log is full (500 records, append-only)"}});
|
||||
return form_ok(env, req, v, "Record appended.",
|
||||
"{\"ok\":true,\"index\":" + std::to_string(hub->chain.records().size() - 1) + "}",
|
||||
201);
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return form_fail(env, req, v, e, in);
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/audit/verify", "audit-verify", [hub](Request) {
|
||||
auto bad = hub->chain.verify();
|
||||
return fw::JsonResponse(std::string("{\"intact\":") + (bad ? "false" : "true") +
|
||||
",\"records\":" + std::to_string(hub->chain.records().size()) +
|
||||
",\"first_broken\":" + (bad ? std::to_string(*bad) : "null") + "}");
|
||||
});
|
||||
router.post("/audit/tamper", "audit-tamper", [hub](Request req) -> Response {
|
||||
std::string idx = get_or(input(req), "index");
|
||||
std::size_t i = 0;
|
||||
if (idx.empty() || idx.size() > 6 || idx.find_first_not_of("0123456789") != std::string::npos)
|
||||
return fw::problem_response(422, "Invalid index", "index must be a number", req.path);
|
||||
i = std::stoul(idx);
|
||||
if (!hub->chain.tamper(i))
|
||||
return fw::problem_response(404, "No such record", "index " + idx, req.path);
|
||||
return fw::JsonResponse("{\"tampered\":" + idx + "}");
|
||||
});
|
||||
|
||||
router.get("/audit/mask", "audit-mask", [](Request req) {
|
||||
std::string email = req.query_or("email", "ada.lovelace@example.com");
|
||||
std::string card = req.query_or("card", "4111 1111 1111 1111");
|
||||
std::string text = req.query_or("text", "mail ada@example.com card 4111 1111 1111 1111 ssn 123-45-6789 from 10.0.0.7");
|
||||
std::size_t hits = 0;
|
||||
std::string red = fw::PiiMasker::redact(text, &hits);
|
||||
return fw::JsonResponse("{\"email\":" + q(fw::PiiMasker::mask_email(email.substr(0, 120))) +
|
||||
",\"card\":" + q(fw::PiiMasker::mask_card(card.substr(0, 40))) +
|
||||
",\"redacted\":" + q(red) + ",\"redactions\":" +
|
||||
std::to_string(hits) + "}");
|
||||
});
|
||||
|
||||
auto retention_json = [hub] {
|
||||
std::string e, x;
|
||||
for (const auto& r : hub->retention.entries())
|
||||
e += std::string(e.empty() ? "" : ",") + "{\"id\":" + q(r.id) + ",\"class\":" + q(r.klass) +
|
||||
",\"age_days\":" + std::to_string(r.age_days) + ",\"hold\":" +
|
||||
(r.hold ? "true" : "false") + "}";
|
||||
for (const auto& id : hub->retention.expired()) x += (x.empty() ? "" : ",") + q(id);
|
||||
return "{\"entries\":[" + e + "],\"expired\":[" + x + "]}";
|
||||
};
|
||||
router.get("/audit/retention", "audit-retention", [env, retention_json, hub](Request req) -> Response {
|
||||
if (json_client(req)) return fw::JsonResponse(retention_json());
|
||||
std::vector<std::vector<std::string>> rows;
|
||||
auto exp = hub->retention.expired();
|
||||
for (const auto& r : hub->retention.entries())
|
||||
rows.push_back({r.id, r.klass, std::to_string(r.age_days),
|
||||
std::to_string(fw::RetentionStore::max_age(r.klass)),
|
||||
r.hold ? "legal hold" : (std::find(exp.begin(), exp.end(), r.id) != exp.end() ? "expired" : "keep")});
|
||||
return page(env, "Retention",
|
||||
table({"Id", "Class", "Age (d)", "Max (d)", "State"}, rows) +
|
||||
form_html("/audit/retention/hold", "Legal hold",
|
||||
{{"id", "Entry id"}, {"hold", "true or false"}}, "Set hold") +
|
||||
form_html("/audit/retention/purge", "Purge expired (dry run unless confirm=yes)",
|
||||
{{"confirm", "Type yes to run"}}, "Purge"));
|
||||
});
|
||||
router.post("/audit/retention/hold", "audit-retention-hold", [hub](Request req) -> Response {
|
||||
auto in = input(req);
|
||||
std::string hold = get_or(in, "hold");
|
||||
if (hold != "true" && hold != "false")
|
||||
return fw::problem_response(422, "Invalid hold", "hold must be true or false", req.path);
|
||||
if (!hub->retention.set_hold(get_or(in, "id"), hold == "true"))
|
||||
return fw::problem_response(404, "No such entry", get_or(in, "id"), req.path);
|
||||
hub->chain.append("system", "legal-hold", get_or(in, "id"), "hold=" + hold);
|
||||
return fw::JsonResponse("{\"ok\":true,\"hold\":" + hold + "}");
|
||||
});
|
||||
router.post("/audit/retention/purge", "audit-retention-purge", [hub](Request req) -> Response {
|
||||
bool confirm = get_or(input(req), "confirm") == "yes";
|
||||
auto exp = hub->retention.expired();
|
||||
std::size_t n = confirm ? hub->retention.purge() : 0;
|
||||
if (confirm) hub->chain.append("system", "purge", "retention", std::to_string(n) + " removed");
|
||||
return fw::JsonResponse(std::string("{\"dry_run\":") + (confirm ? "false" : "true") +
|
||||
",\"would_purge\":" + std::to_string(exp.size()) +
|
||||
",\"purged\":" + std::to_string(n) + "}");
|
||||
});
|
||||
|
||||
auto erase_view = [] {
|
||||
FormView v;
|
||||
v.title = "Data subject erasure";
|
||||
v.action = "/audit/subject/erase";
|
||||
v.submit = "Erase";
|
||||
v.fields = {{"subject", "Subject email", "email", "cascades across all tables"},
|
||||
{"confirm", "Confirm", "text", "type yes to erase"}};
|
||||
return v;
|
||||
};
|
||||
router.get("/audit/subject", "audit-subject", [env, erase_view](Request) {
|
||||
FormView v = erase_view();
|
||||
v.notice = "Export first: /audit/subject/export?subject=ada@example.com";
|
||||
return form_page(env, v);
|
||||
});
|
||||
router.get("/audit/subject/export", "audit-subject-export", [hub](Request req) -> Response {
|
||||
std::string s = req.query_or("subject", "");
|
||||
if (s.empty() || s.size() > 120)
|
||||
return fw::problem_response(400, "Missing subject", "?subject= is required", req.path);
|
||||
std::string out;
|
||||
for (const auto& [t, rows] : hub->subjects.export_for(s)) {
|
||||
std::string r;
|
||||
for (const auto& x : rows) r += (r.empty() ? "" : ",") + q(x);
|
||||
out += std::string(out.empty() ? "" : ",") + q(t) + ":[" + r + "]";
|
||||
}
|
||||
return fw::JsonResponse("{\"subject\":" + q(s) + ",\"data\":{" + out + "}}");
|
||||
});
|
||||
router.post("/audit/subject/erase", "audit-subject-erase",
|
||||
[hub, env, erase_view](Request req) -> Response {
|
||||
FormView v = erase_view();
|
||||
auto in = input(req);
|
||||
fw::Model m({{"subject", fw::FieldType::Email, true, 3, 120, 0, 0, false, ""},
|
||||
{"confirm", fw::FieldType::String, true, 1, 8, 0, 0, false, ""}});
|
||||
try {
|
||||
auto c = m.validate(in);
|
||||
if (c["confirm"] != "yes") throw fw::ValidationError({{"confirm", "type yes to confirm"}});
|
||||
std::size_t n = hub->subjects.erase(c["subject"]);
|
||||
hub->chain.append("system", "erasure", fw::sha256_hex(c["subject"]).substr(0, 16),
|
||||
std::to_string(n) + " rows removed");
|
||||
return form_ok(env, req, v, std::to_string(n) + " rows erased.",
|
||||
"{\"ok\":true,\"erased\":" + std::to_string(n) + "}");
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return form_fail(env, req, v, e, in);
|
||||
}
|
||||
});
|
||||
|
||||
services.add_feature("Hash-chained audit log", "/audit/log");
|
||||
services.add_feature("Audit tamper detection", "/audit/verify");
|
||||
services.add_feature("PII masking and redaction", "/audit/mask");
|
||||
services.add_feature("Retention and legal hold", "/audit/retention");
|
||||
services.add_feature("Data subject export and erasure", "/audit/subject");
|
||||
}
|
||||
|
||||
// ---- governance ------------------------------------------------------------
|
||||
void register_governance(fw::Router& router, Services& services, const HubPtr& hub,
|
||||
fw::Environment* env) {
|
||||
auto key_view = [] {
|
||||
FormView v;
|
||||
v.title = "Issue an API key";
|
||||
v.action = "/governance/keys";
|
||||
v.submit = "Issue";
|
||||
v.fields = {{"owner", "Owner", "text", ""},
|
||||
{"tier", "Tier", "text", "free or pro"},
|
||||
{"scopes", "Scopes", "text", "comma separated, e.g. read,write"}};
|
||||
return v;
|
||||
};
|
||||
router.get("/governance/keys", "governance-keys-form", [env, key_view](Request) {
|
||||
FormView v = key_view();
|
||||
return form_page(env, v);
|
||||
});
|
||||
router.post("/governance/keys", "governance-keys", [hub, env, key_view](Request req) -> Response {
|
||||
FormView v = key_view();
|
||||
auto in = input(req);
|
||||
fw::Model m({{"owner", fw::FieldType::String, true, 1, 60, 0, 0, false, ""},
|
||||
{"tier", fw::FieldType::String, false, 0, 8, 0, 0, false, "free"},
|
||||
{"scopes", fw::FieldType::String, false, 0, 100, 0, 0, false, "read"}});
|
||||
try {
|
||||
auto c = m.validate(in);
|
||||
if (c["tier"] != "free" && c["tier"] != "pro")
|
||||
throw fw::ValidationError({{"tier", "must be free or pro"}});
|
||||
std::set<std::string> scopes;
|
||||
std::stringstream ss(c["scopes"]);
|
||||
for (std::string s; std::getline(ss, s, ',');)
|
||||
if (!s.empty()) scopes.insert(s);
|
||||
std::string id;
|
||||
std::string key = hub->keys.issue(c["owner"], c["tier"], scopes, &id);
|
||||
if (key.empty()) throw fw::ValidationError({{"owner", "key cap reached (64)"}});
|
||||
return form_ok(env, req, v, "Key " + id + ": " + key + " (shown once)",
|
||||
"{\"id\":" + q(id) + ",\"key\":" + q(key) + "}", 201);
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return form_fail(env, req, v, e, in);
|
||||
}
|
||||
});
|
||||
router.post("/governance/keys/{id}/revoke", "governance-keys-revoke", [hub](Request req) -> Response {
|
||||
if (!hub->keys.revoke(req.param_or("id", "")))
|
||||
return fw::problem_response(404, "No such key", req.param_or("id", ""), req.path);
|
||||
return fw::JsonResponse("{\"revoked\":true}");
|
||||
});
|
||||
|
||||
router.get("/governance/whoami", "governance-whoami", [hub](Request req) -> Response {
|
||||
const fw::ApiKeyInfo* info = nullptr;
|
||||
switch (hub->keys.authenticate(req.headers.get("X-API-Key"), "read", &info)) {
|
||||
case fw::KeyResult::Ok: break;
|
||||
case fw::KeyResult::Missing:
|
||||
return fw::problem_response(401, "Missing key", "send X-API-Key", req.path);
|
||||
case fw::KeyResult::Unknown:
|
||||
return fw::problem_response(401, "Unknown key", "key not recognised", req.path);
|
||||
case fw::KeyResult::Revoked:
|
||||
return fw::problem_response(401, "Revoked key", "key was revoked", req.path);
|
||||
case fw::KeyResult::Forbidden:
|
||||
return fw::problem_response(403, "Missing scope", "scope read required", req.path);
|
||||
}
|
||||
fw::TierPolicy tier = fw::TierTable::find(info->tier);
|
||||
bool ok = hub->ledger.charge(info->id, tier);
|
||||
Response r = ok ? fw::JsonResponse("{\"id\":" + q(info->id) + ",\"owner\":" + q(info->owner) +
|
||||
",\"tier\":" + q(tier.name) + "}")
|
||||
: fw::problem_response(429, "Rate limit exceeded", "tier " + tier.name, req.path);
|
||||
hub->ledger.headers(info->id, tier, r.headers);
|
||||
return r;
|
||||
});
|
||||
router.get("/governance/tiers", "governance-tiers", [](Request) {
|
||||
auto t = [](const char* n) {
|
||||
auto p = fw::TierTable::find(n);
|
||||
return "{\"tier\":" + q(p.name) + ",\"per_min\":" + std::to_string(p.per_min) + "}";
|
||||
};
|
||||
return fw::JsonResponse("{\"tiers\":[" + t("free") + "," + t("pro") + "]}");
|
||||
});
|
||||
|
||||
auto item = [hub](const char* ver) {
|
||||
return [hub, ver](Request) {
|
||||
Response r = fw::JsonResponse(std::string("{\"version\":\"") + ver + "\",\"items\":[1,2,3]}");
|
||||
hub->versions.annotate(ver, r.headers);
|
||||
return r;
|
||||
};
|
||||
};
|
||||
router.get("/v1/items", "v1-items", item("v1"));
|
||||
router.get("/v2/items", "v2-items", item("v2"));
|
||||
router.get("/governance/versions", "governance-versions", [hub](Request) {
|
||||
std::string out;
|
||||
for (const auto& v : hub->versions.all())
|
||||
out += std::string(out.empty() ? "" : ",") + "{\"version\":" + q(v.name) +
|
||||
",\"deprecated\":" + (v.deprecated ? "true" : "false") +
|
||||
",\"sunset\":" + q(v.sunset) + "}";
|
||||
return fw::JsonResponse("{\"versions\":[" + out + "]}");
|
||||
});
|
||||
|
||||
auto lint_view = [] {
|
||||
FormView v;
|
||||
v.title = "Route linter";
|
||||
v.action = "/governance/lint";
|
||||
v.submit = "Lint";
|
||||
v.fields = {{"paths", "Paths", "textarea", "one path per line, max 100"}};
|
||||
return v;
|
||||
};
|
||||
router.get("/governance/lint", "governance-lint-form", [env, lint_view](Request) {
|
||||
FormView v = lint_view();
|
||||
return form_page(env, v);
|
||||
});
|
||||
router.post("/governance/lint", "governance-lint", [env, lint_view](Request req) -> Response {
|
||||
FormView v = lint_view();
|
||||
auto in = input(req);
|
||||
fw::Model m({{"paths", fw::FieldType::String, true, 1, 4000, 0, 0, false, ""}});
|
||||
try {
|
||||
auto c = m.validate(in);
|
||||
std::vector<std::string> paths;
|
||||
std::stringstream ss(c["paths"]);
|
||||
for (std::string s; std::getline(ss, s);) {
|
||||
while (!s.empty() && (s.back() == '\r' || s.back() == ' ')) s.pop_back();
|
||||
if (!s.empty()) paths.push_back(s);
|
||||
}
|
||||
auto findings = fw::RouteLinter::lint(paths);
|
||||
std::string out, text;
|
||||
for (const auto& f : findings) {
|
||||
out += std::string(out.empty() ? "" : ",") + "{\"path\":" + q(f.path) + ",\"rule\":" + q(f.rule) + "}";
|
||||
text += f.path + " " + f.rule + "; ";
|
||||
}
|
||||
return form_ok(env, req, v, findings.empty() ? "No findings." : text,
|
||||
"{\"findings\":[" + out + "]}");
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return form_fail(env, req, v, e, in);
|
||||
}
|
||||
});
|
||||
|
||||
auto diff_view = [] {
|
||||
FormView v;
|
||||
v.title = "Spec differ";
|
||||
v.action = "/governance/diff";
|
||||
v.submit = "Compare";
|
||||
v.fields = {{"before", "Before", "textarea", "METHOD /path required=a,b optional=c"},
|
||||
{"after", "After", "textarea", ""}};
|
||||
return v;
|
||||
};
|
||||
router.get("/governance/diff", "governance-diff-form", [env, diff_view](Request) {
|
||||
FormView v = diff_view();
|
||||
return form_page(env, v);
|
||||
});
|
||||
router.post("/governance/diff", "governance-diff", [env, diff_view](Request req) -> Response {
|
||||
FormView v = diff_view();
|
||||
auto in = input(req);
|
||||
fw::Model m({{"before", fw::FieldType::String, true, 1, 8000, 0, 0, false, ""},
|
||||
{"after", fw::FieldType::String, true, 1, 8000, 0, 0, false, ""}});
|
||||
try {
|
||||
auto c = m.validate(in);
|
||||
auto findings = fw::SpecDiffer::diff(c["before"], c["after"]);
|
||||
std::string out, text;
|
||||
std::size_t breaking = 0;
|
||||
for (const auto& f : findings) {
|
||||
if (f.kind == "breaking") ++breaking;
|
||||
out += std::string(out.empty() ? "" : ",") + "{\"kind\":" + q(f.kind) +
|
||||
",\"operation\":" + q(f.operation) + ",\"detail\":" + q(f.detail) + "}";
|
||||
text += f.kind + ": " + f.operation + " " + f.detail + "; ";
|
||||
}
|
||||
return form_ok(env, req, v, findings.empty() ? "No changes." : text,
|
||||
"{\"breaking\":" + std::to_string(breaking) + ",\"findings\":[" + out + "]}");
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return form_fail(env, req, v, e, in);
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/governance/problem", "governance-problem", [](Request) {
|
||||
return fw::JsonResponse("{\"try\":\"/governance/problem/404\",\"format\":\"RFC 7807\"}");
|
||||
});
|
||||
router.get("/governance/problem/{status}", "governance-problem-status", [](Request req) -> Response {
|
||||
std::string s = req.param_or("status", "");
|
||||
if (s.size() != 3 || s.find_first_not_of("0123456789") != std::string::npos ||
|
||||
std::stoi(s) < 400 || std::stoi(s) > 599)
|
||||
return fw::problem_response(400, "Bad status", "status must be 400-599", req.path);
|
||||
int st = std::stoi(s);
|
||||
return fw::problem_response(st, fw::status_text(st), "Example problem for " + s, req.path);
|
||||
});
|
||||
|
||||
services.add_feature("API keys with scopes", "/governance/keys");
|
||||
services.add_feature("Tiers and rate limit headers", "/governance/tiers");
|
||||
services.add_feature("API versions (Deprecation, Sunset)", "/v1/items");
|
||||
services.add_feature("API version list", "/governance/versions");
|
||||
services.add_feature("Route linter", "/governance/lint");
|
||||
services.add_feature("OpenAPI spec differ", "/governance/diff");
|
||||
services.add_feature("RFC 7807 problem+json", "/governance/problem");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_enterprise_demo(fw::Router& router, Services& services) {
|
||||
auto hub = std::make_shared<Hub>();
|
||||
fw::Environment* env = services.templates.get();
|
||||
env->add_template("ent_page.html",
|
||||
"{% extends \"base.html\" %}{% block content %}<h1>{{ heading }}</h1>"
|
||||
"{{ body|safe }}{% endblock %}");
|
||||
register_tenancy(router, services, hub, env);
|
||||
register_audit(router, services, hub, env);
|
||||
register_governance(router, services, hub, env);
|
||||
}
|
||||
|
||||
} // namespace molo::example::app
|
||||
@@ -10,8 +10,8 @@ namespace {
|
||||
|
||||
const char* kFeatures[][2] = {
|
||||
{"routing", "/routing/hello/world"},
|
||||
{"views", "/views/greet"},
|
||||
{"routers", "/routers/nested/deep"},
|
||||
{"views", "/routing/views/greet"},
|
||||
{"routers", "/routing/routers/nested/deep"},
|
||||
{"chaining", "/app1/app1/app1/whoami"},
|
||||
{"orm-sqlite", "/orm/users?backend=sqlite"},
|
||||
{"orm-postgres", "/orm/users?backend=postgres"},
|
||||
@@ -50,9 +50,10 @@ const char* kFeatures[][2] = {
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_index(fw::Router& router, Services& services) {
|
||||
fw::Environment* env = services.templates.get();
|
||||
router.get("/", "index", [env](fw::Request req) {
|
||||
void register_index(fw::Router& router, Services& services_ref) {
|
||||
fw::Environment* env = services_ref.templates.get();
|
||||
Services* services = &services_ref;
|
||||
router.get("/", "index", [env, services](fw::Request req) {
|
||||
fw::TemplateCtx ctx;
|
||||
ctx["title"] = std::string("MoloApp living example");
|
||||
ctx["show_matrix"] = std::string("true");
|
||||
@@ -60,6 +61,9 @@ void register_index(fw::Router& router, Services& services) {
|
||||
for (const auto& [feature, route] : kFeatures) {
|
||||
rows.push_back({{"feature", feature}, {"route", route}});
|
||||
}
|
||||
for (const auto& [feature, route] : services->features) {
|
||||
rows.push_back({{"feature", feature}, {"route", route}});
|
||||
}
|
||||
ctx["matrix"] = rows;
|
||||
(void)req;
|
||||
return fw::Response(200, env->render("index.html", ctx),
|
||||
|
||||
@@ -186,6 +186,13 @@ void register_ops_demo(fw::Router& router, Services& services) {
|
||||
return fw::JsonResponse(body, 200);
|
||||
});
|
||||
|
||||
router.get("/workflow/release", "workflow-usage", [](fw::Request req) {
|
||||
(void)req;
|
||||
return fw::JsonResponse(
|
||||
"{\"usage\":\"POST commits=feat: add x|fix: y (Conventional "
|
||||
"Commits separated by |)\",\"base_version\":\"0.1.0\"}",
|
||||
200);
|
||||
});
|
||||
router.post("/workflow/release", "workflow", [](fw::Request req) {
|
||||
auto input = fw::parse_json_object_flat(req.body);
|
||||
if (input.empty()) input = fw::parse_form(req.body);
|
||||
|
||||
@@ -0,0 +1,586 @@
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "App.hpp"
|
||||
#include "FormUi.hpp"
|
||||
#include "../fw/Cookies.hpp"
|
||||
#include "../fw/Platform.hpp"
|
||||
#include "../fw/Router.hpp"
|
||||
#include "../fw/Templates.hpp"
|
||||
#include "../fw/Validate.hpp"
|
||||
|
||||
namespace molo::example::app {
|
||||
|
||||
namespace {
|
||||
|
||||
namespace pc = fw::platform_caps;
|
||||
|
||||
std::string esc(const std::string& s) { return fw::html_escape(s); }
|
||||
|
||||
bool parse_long_in(const std::string& s, long lo, long hi, long& out) {
|
||||
if (s.empty() || s.size() > 12) return false;
|
||||
std::size_t i = (s[0] == '-') ? 1 : 0;
|
||||
if (i == s.size()) return false;
|
||||
for (std::size_t k = i; k < s.size(); ++k)
|
||||
if (s[k] < '0' || s[k] > '9') return false;
|
||||
out = std::atol(s.c_str());
|
||||
return out >= lo && out <= hi;
|
||||
}
|
||||
|
||||
// All state of this feature group lives here, shared by the route lambdas.
|
||||
class PlatformDemo {
|
||||
public:
|
||||
PlatformDemo(Services& services)
|
||||
: env_(services.templates.get()),
|
||||
prom_(services.metrics.get(), services.stats.get()) {
|
||||
env_->add_template(
|
||||
"platform_page.html",
|
||||
"{% extends \"base.html\" %}{% block content %}<h1>{{ title }}</h1>"
|
||||
"{{ body|safe }}{% endblock %}");
|
||||
seed_catalog();
|
||||
for (const char* t : {"templates", "embedded-assets", "seed-data"})
|
||||
health_.add_startup_task(t, true);
|
||||
for (const char* c : {"database", "cache", "workers"})
|
||||
health_.add_check(c, true);
|
||||
seed_di();
|
||||
logs_.log(fw::LogLevel::Info, "platform demo ready", "boot");
|
||||
doc_ = "Conditional GET demo document.\n0123456789abcdefghijklmnopqrstuvwxyz\n";
|
||||
}
|
||||
|
||||
void mount(fw::Router& r);
|
||||
|
||||
private:
|
||||
fw::Response page(const std::string& title, const std::string& body,
|
||||
int status = 200) const {
|
||||
fw::TemplateCtx ctx;
|
||||
ctx["title"] = title;
|
||||
ctx["body"] = body;
|
||||
return fw::Response(status, env_->render("platform_page.html", ctx),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
fw::Response form_page(const FormView& v, int status = 200) const {
|
||||
return fw::Response(status, env_->render("form_page.html", v.ctx()),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
static fw::Response json(const std::string& body, int status = 200) {
|
||||
fw::Response r(status, body, "application/json");
|
||||
r.headers.set("Cache-Control", "no-store");
|
||||
return r;
|
||||
}
|
||||
static fw::Response see_other(const std::string& to) {
|
||||
fw::Response r(303, "", "text/plain; charset=utf-8");
|
||||
r.headers.set("Location", to);
|
||||
return r;
|
||||
}
|
||||
fw::Response invalid(const FormView& base, const fw::Request& req,
|
||||
const fw::ValidationError& e) const {
|
||||
if (!wants_html(req)) return json(e.to_json(), 422);
|
||||
FormView v = base;
|
||||
v.values = fw::parse_form(req.body);
|
||||
v.error = &e;
|
||||
return form_page(v, 422);
|
||||
}
|
||||
static std::string corr(const fw::Request& req) {
|
||||
std::string c = req.headers.get("X-Correlation-ID");
|
||||
return c.empty() ? req.correlation_id : c;
|
||||
}
|
||||
|
||||
void seed_catalog();
|
||||
void seed_di();
|
||||
void mount_i18n(fw::Router& r);
|
||||
void mount_http(fw::Router& r);
|
||||
void mount_ops(fw::Router& r);
|
||||
void mount_observability(fw::Router& r);
|
||||
void mount_app(fw::Router& r);
|
||||
void mount_expose(fw::Router& r);
|
||||
|
||||
fw::Environment* env_;
|
||||
fw::MessageCatalog catalog_;
|
||||
fw::HealthRegistry health_;
|
||||
fw::PrometheusExporter prom_;
|
||||
fw::LogRing logs_;
|
||||
fw::TraceContextFactory trace_;
|
||||
fw::ServiceRegistry di_;
|
||||
fw::ExposeStats expose_;
|
||||
std::mutex doc_mu_;
|
||||
std::string doc_;
|
||||
std::shared_ptr<unsigned long> instance_counter_ =
|
||||
std::make_shared<unsigned long>(0);
|
||||
};
|
||||
|
||||
void PlatformDemo::seed_catalog() {
|
||||
catalog_.add("en", "welcome", {"Welcome"});
|
||||
catalog_.add("en", "items", {"%d item", "%d items"});
|
||||
catalog_.add("nl", "welcome", {"Welkom"});
|
||||
catalog_.add("nl", "items", {"%d item", "%d items"});
|
||||
catalog_.add("de", "welcome", {"Willkommen"});
|
||||
catalog_.add("de", "items", {"%d Artikel", "%d Artikel"});
|
||||
catalog_.add("fr", "welcome", {"Bienvenue"});
|
||||
catalog_.add("fr", "items", {"%d article", "%d articles"});
|
||||
catalog_.add("ru", "welcome", {"Добро пожаловать"});
|
||||
catalog_.add("ru", "items", {"%d предмет", "%d предмета", "%d предметов"});
|
||||
catalog_.add("ja", "welcome", {"ようこそ"});
|
||||
catalog_.add("ja", "items", {"%d 個"});
|
||||
}
|
||||
|
||||
void PlatformDemo::seed_di() {
|
||||
auto counter = instance_counter_;
|
||||
auto make = [counter](std::string prefix) {
|
||||
return [counter, prefix]() { return prefix + "#" + std::to_string(++*counter); };
|
||||
};
|
||||
di_.add("config", fw::Lifetime::Singleton, make("Config"));
|
||||
di_.add("logger", fw::Lifetime::Singleton, make("Logger"));
|
||||
di_.add("request-context", fw::Lifetime::Scoped, make("RequestContext"));
|
||||
di_.add("mailer", fw::Lifetime::Transient, make("Mailer"));
|
||||
}
|
||||
|
||||
void PlatformDemo::mount_i18n(fw::Router& r) {
|
||||
r.get("/i18n", "i18n-page", [this](fw::Request req) {
|
||||
std::string lang_param = req.query_or("lang", "");
|
||||
std::string accept = req.headers.get("Accept-Language");
|
||||
std::string locale = fw::negotiate_locale(lang_param, accept, catalog_);
|
||||
std::string source = catalog_.has_locale(fw::negotiate_locale(lang_param, "", catalog_)) &&
|
||||
!lang_param.empty() &&
|
||||
fw::negotiate_locale(lang_param, "", catalog_) == locale
|
||||
? "?lang parameter"
|
||||
: (locale != catalog_.default_locale() ? "Accept-Language header"
|
||||
: "default");
|
||||
std::string n_text = req.query_or("n", "3");
|
||||
long n = 0;
|
||||
std::string n_error;
|
||||
if (!parse_long_in(n_text, 0, pc::kMaxPluralN, n))
|
||||
n_error = "must be a whole number from 0 to " + std::to_string(pc::kMaxPluralN);
|
||||
std::string body = "<p>Active locale: <strong>" + esc(locale) +
|
||||
"</strong> <span class=\"hint\">(from " + source + ")</span></p>";
|
||||
body += "<form method=\"get\" action=\"/i18n\"><div class=\"field\">"
|
||||
"<label for=\"f-lang\">Language</label><select id=\"f-lang\" name=\"lang\">";
|
||||
for (const auto& l : catalog_.locales())
|
||||
body += "<option value=\"" + l + "\"" + (l == locale ? " selected" : "") +
|
||||
">" + l + "</option>";
|
||||
body += "</select></div><div class=\"field" + std::string(n_error.empty() ? "" : " invalid") +
|
||||
"\"><label for=\"f-n\">Count</label><input id=\"f-n\" type=\"number\" name=\"n\" value=\"" +
|
||||
esc(n_text) + "\">";
|
||||
if (!n_error.empty())
|
||||
body += "<p class=\"field-error\" id=\"e-n\">" + esc(n_error) + "</p>";
|
||||
body += "</div><button type=\"submit\">Translate</button></form>";
|
||||
if (n_error.empty()) {
|
||||
body += "<h2>" + esc(catalog_.translate(locale, "welcome")) + "</h2>";
|
||||
body += "<p id=\"plural\">" + esc(catalog_.translate(locale, "items", n)) + "</p>";
|
||||
body += "<p class=\"hint\">Plural form " +
|
||||
std::to_string(fw::PluralRule::index(locale, n)) + " of " +
|
||||
std::to_string(fw::PluralRule::forms(locale)) + ".</p>";
|
||||
}
|
||||
body += "<p>Switch: ";
|
||||
for (const auto& l : catalog_.locales())
|
||||
body += "<a href=\"/i18n?lang=" + l + "&n=" + (n_error.empty() ? std::to_string(n) : "3") +
|
||||
"\">" + l + "</a> ";
|
||||
body += "</p><p><a href=\"/i18n/po?lang=" + locale + "\">catalog as .po</a></p>";
|
||||
fw::Response res = page("Internationalisation", body, n_error.empty() ? 200 : 422);
|
||||
res.headers.set("Content-Language", locale);
|
||||
res.headers.set("Vary", "Accept-Language");
|
||||
return res;
|
||||
});
|
||||
|
||||
r.get("/i18n/po", "i18n-po", [this](fw::Request req) {
|
||||
std::string locale = req.query_or("lang", "en");
|
||||
if (!catalog_.has_locale(locale))
|
||||
return fw::Response(404, "unknown locale\n", "text/plain; charset=utf-8");
|
||||
return fw::Response(200, catalog_.to_po(locale), "text/plain; charset=utf-8");
|
||||
});
|
||||
}
|
||||
|
||||
void PlatformDemo::mount_http(fw::Router& r) {
|
||||
r.get("/compress/demo", "compress-demo", [](fw::Request req) {
|
||||
long size = 2000;
|
||||
if (req.query.count("size") &&
|
||||
!parse_long_in(req.query_or("size", ""), 0, (long)pc::kMaxCompressBody, size))
|
||||
return fw::Response(422, "size must be 0 to " + std::to_string(pc::kMaxCompressBody) + "\n",
|
||||
"text/plain; charset=utf-8");
|
||||
std::string body;
|
||||
const std::string unit = "MoloApp compresses repetitive text well. ";
|
||||
while ((long)body.size() < size) body += unit;
|
||||
body.resize((std::size_t)size);
|
||||
fw::Response res(200, body, "text/plain; charset=utf-8");
|
||||
res.headers.set("Vary", "Accept-Encoding");
|
||||
res.headers.set("X-Original-Length", std::to_string(body.size()));
|
||||
if (body.size() >= pc::kCompressMin &&
|
||||
fw::accepts_encoding(req.headers.get("Accept-Encoding"), "gzip")) {
|
||||
res.body = fw::gzip_stored(body);
|
||||
res.headers.set("Content-Encoding", "gzip");
|
||||
}
|
||||
return res;
|
||||
});
|
||||
|
||||
r.get("/conditional/doc", "conditional-get", [this](fw::Request req) {
|
||||
std::string doc;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(doc_mu_);
|
||||
doc = doc_;
|
||||
}
|
||||
std::string etag = fw::make_etag(doc);
|
||||
fw::Response res(200, doc, "text/plain; charset=utf-8");
|
||||
res.headers.set("ETag", etag);
|
||||
res.headers.set("Accept-Ranges", "bytes");
|
||||
res.headers.set("Cache-Control", "no-cache");
|
||||
if (fw::etag_matches(req.headers.get("If-None-Match"), etag)) {
|
||||
res.status = 304;
|
||||
res.body.clear();
|
||||
return res;
|
||||
}
|
||||
fw::ByteRange range = fw::parse_range(req.headers.get("Range"), doc.size());
|
||||
if (range.kind == fw::ByteRange::Kind::Unsatisfiable) {
|
||||
res.status = 416;
|
||||
res.body.clear();
|
||||
res.headers.set("Content-Range", "bytes */" + std::to_string(doc.size()));
|
||||
} else if (range.kind == fw::ByteRange::Kind::Ok) {
|
||||
res.status = 206;
|
||||
res.body = doc.substr(range.first, range.last - range.first + 1);
|
||||
res.headers.set("Content-Range", "bytes " + std::to_string(range.first) + "-" +
|
||||
std::to_string(range.last) + "/" +
|
||||
std::to_string(doc.size()));
|
||||
}
|
||||
return res;
|
||||
});
|
||||
|
||||
r.post("/conditional/doc", "conditional-put", [this](fw::Request req) {
|
||||
if (req.body.size() > pc::kMaxDocBytes)
|
||||
return json("{\"error\":\"too_large\",\"max\":" + std::to_string(pc::kMaxDocBytes) + "}", 413);
|
||||
if (req.body.empty())
|
||||
return json("{\"error\":\"validation\",\"message\":\"body is required\"}", 422);
|
||||
std::lock_guard<std::mutex> lock(doc_mu_);
|
||||
std::string match = req.headers.get("If-Match");
|
||||
if (!match.empty() && !fw::etag_matches(match, fw::make_etag(doc_)))
|
||||
return json("{\"error\":\"precondition_failed\",\"etag\":\"" +
|
||||
fw::json_escape(fw::make_etag(doc_)) + "\"}", 412);
|
||||
doc_ = req.body;
|
||||
fw::Response res = json("{\"bytes\":" + std::to_string(doc_.size()) + "}");
|
||||
res.headers.set("ETag", fw::make_etag(doc_));
|
||||
return res;
|
||||
});
|
||||
}
|
||||
|
||||
void PlatformDemo::mount_ops(fw::Router& r) {
|
||||
r.get("/healthz", "healthz", [this](fw::Request) { return json(health_.liveness_json()); });
|
||||
r.get("/readyz", "readyz", [this](fw::Request) {
|
||||
return json(health_.readiness_json(), health_.ready() ? 200 : 503);
|
||||
});
|
||||
r.get("/startupz", "startupz", [this](fw::Request) {
|
||||
return json(health_.startup_json(), health_.startup_complete() ? 200 : 503);
|
||||
});
|
||||
r.post("/readyz/checks/{name}", "readyz-toggle", [this](fw::Request req) {
|
||||
std::string state = req.query_or("state", "");
|
||||
if (state != "up" && state != "down")
|
||||
return json("{\"error\":\"validation\",\"message\":\"state must be up or down\"}", 422);
|
||||
if (!health_.set_check(req.param_or("name", ""), state == "up"))
|
||||
return json("{\"error\":\"not_found\",\"message\":\"unknown check\"}", 404);
|
||||
return json(health_.readiness_json(), health_.ready() ? 200 : 503);
|
||||
});
|
||||
r.post("/startupz/tasks/{name}", "startupz-toggle", [this](fw::Request req) {
|
||||
std::string state = req.query_or("state", "");
|
||||
if (state != "done" && state != "pending")
|
||||
return json("{\"error\":\"validation\",\"message\":\"state must be done or pending\"}", 422);
|
||||
if (!health_.set_startup_task(req.param_or("name", ""), state == "done"))
|
||||
return json("{\"error\":\"not_found\",\"message\":\"unknown task\"}", 404);
|
||||
return json(health_.startup_json(), health_.startup_complete() ? 200 : 503);
|
||||
});
|
||||
r.get("/metrics", "prometheus", [this](fw::Request) {
|
||||
return fw::Response(200, prom_.render(), "text/plain; version=0.0.4; charset=utf-8");
|
||||
});
|
||||
}
|
||||
|
||||
void PlatformDemo::mount_observability(fw::Router& r) {
|
||||
auto emit_view = []() {
|
||||
FormView v;
|
||||
v.title = "Write a log record";
|
||||
v.action = "/logging/emit";
|
||||
v.submit = "Log";
|
||||
v.fields = {{"level", "Level", "text", "debug, info, warn or error"},
|
||||
{"message", "Message", "text", "secrets like password=x are redacted"}};
|
||||
return v;
|
||||
};
|
||||
r.get("/logging/emit", "logging-form", [this, emit_view](fw::Request) {
|
||||
return form_page(emit_view());
|
||||
});
|
||||
r.post("/logging/emit", "logging-emit", [this, emit_view](fw::Request req) {
|
||||
auto input = fw::parse_form(req.body);
|
||||
if (req.headers.get("Content-Type").find("application/json") != std::string::npos)
|
||||
input = fw::parse_json_object_flat(req.body);
|
||||
std::vector<fw::FieldError> fails;
|
||||
fw::LogLevel level = fw::LogLevel::Info;
|
||||
if (input["level"].empty()) fails.push_back({"level", "is required"});
|
||||
else if (!fw::parse_level(input["level"], level))
|
||||
fails.push_back({"level", "must be debug, info, warn or error"});
|
||||
if (input["message"].empty()) fails.push_back({"message", "is required"});
|
||||
else if (input["message"].size() > 300)
|
||||
fails.push_back({"message", "must be at most 300 characters"});
|
||||
if (!fails.empty()) return invalid(emit_view(), req, fw::ValidationError(fails));
|
||||
logs_.log(level, input["message"], corr(req));
|
||||
if (!wants_html(req)) return json("{\"ok\":true,\"size\":" + std::to_string(logs_.size()) + "}");
|
||||
return see_other("/logging/records");
|
||||
});
|
||||
r.get("/logging/records", "logging-records", [this](fw::Request req) {
|
||||
long n = 20;
|
||||
fw::LogLevel min = fw::LogLevel::Debug;
|
||||
if (req.query.count("n") && !parse_long_in(req.query_or("n", ""), 1, 100, n))
|
||||
return page("Log records", "<p class=\"error\">n must be a whole number from 1 to 100</p>", 422);
|
||||
if (req.query.count("level") && !fw::parse_level(req.query_or("level", ""), min))
|
||||
return page("Log records", "<p class=\"error\">level must be debug, info, warn or error</p>", 422);
|
||||
auto recs = logs_.last((std::size_t)n, min);
|
||||
if (req.query_or("format", "") == "json") {
|
||||
std::string out;
|
||||
for (const auto& rec : recs) out += fw::LogRing::to_json(rec) + "\n";
|
||||
return fw::Response(200, out, "application/x-ndjson");
|
||||
}
|
||||
std::string body = "<p class=\"hint\">Ring keeps the last " + std::to_string(pc::kLogRing) +
|
||||
" records (now " + std::to_string(logs_.size()) + "). Showing " +
|
||||
std::to_string(recs.size()) + ". <a href=\"/logging/emit\">Write one</a>, "
|
||||
"<a href=\"/logging/records?format=json\">JSON lines</a>.</p>"
|
||||
"<div class=\"scroll\"><table><thead><tr><th>#</th><th>Level</th>"
|
||||
"<th>Message</th><th>Correlation</th></tr></thead><tbody>";
|
||||
for (const auto& rec : recs)
|
||||
body += "<tr><td>" + std::to_string(rec.seq) + "</td><td>" + fw::level_name(rec.level) +
|
||||
"</td><td>" + esc(rec.message) + "</td><td>" + esc(rec.correlation_id) + "</td></tr>";
|
||||
body += "</tbody></table></div>";
|
||||
return page("Log records", body);
|
||||
});
|
||||
|
||||
r.get("/context/trace", "context-trace", [this](fw::Request req) {
|
||||
fw::TraceContext ctx = trace_.from_header(req.headers.get("traceparent"));
|
||||
std::string cid = corr(req);
|
||||
std::string out = "{\"correlation_id\":\"" + fw::json_escape(cid) +
|
||||
"\",\"continued\":" + (ctx.parent_span_id.empty() ? "false" : "true") +
|
||||
",\"parent_valid\":" + (ctx.parent_valid ? "true" : "false") +
|
||||
",\"trace_id\":\"" + ctx.trace_id + "\",\"parent_span_id\":\"" +
|
||||
ctx.parent_span_id + "\",\"span_id\":\"" + ctx.span_id +
|
||||
"\",\"traceparent\":\"" + ctx.traceparent() + "\"}";
|
||||
fw::Response res = json(out);
|
||||
res.headers.set("traceparent", ctx.traceparent());
|
||||
res.headers.set("X-Correlation-ID", cid);
|
||||
return res;
|
||||
});
|
||||
}
|
||||
|
||||
void PlatformDemo::mount_app(fw::Router& r) {
|
||||
r.get("/di/services", "di-services", [this](fw::Request) {
|
||||
std::string body = "<div class=\"scroll\"><table><thead><tr><th>Service</th><th>Lifetime</th>"
|
||||
"<th>Created</th><th>Resolved</th></tr></thead><tbody>";
|
||||
for (const auto& e : di_.list())
|
||||
body += "<tr><td><a href=\"/di/resolve/" + esc(e.name) + "\">" + esc(e.name) + "</a></td><td>" +
|
||||
fw::lifetime_name(e.lifetime) + "</td><td>" + std::to_string(e.created) +
|
||||
"</td><td>" + std::to_string(e.resolved) + "</td></tr>";
|
||||
body += "</tbody></table></div><p class=\"hint\">Singletons are built once, scoped once per "
|
||||
"?scope= key, transients on every resolve.</p>";
|
||||
return page("Dependency injection", body);
|
||||
});
|
||||
r.get("/di/resolve/{name}", "di-resolve", [this](fw::Request req) {
|
||||
std::string name = req.param_or("name", "");
|
||||
std::string instance;
|
||||
if (!di_.resolve(name, req.query_or("scope", "default"), instance))
|
||||
return json("{\"error\":\"not_found\",\"message\":\"unknown service\"}", 404);
|
||||
return json("{\"name\":\"" + fw::json_escape(name) + "\",\"instance\":\"" +
|
||||
fw::json_escape(instance) + "\"}");
|
||||
});
|
||||
|
||||
FormView flash_view;
|
||||
flash_view.title = "Set a flash message";
|
||||
flash_view.action = "/flash/set";
|
||||
flash_view.submit = "Save and redirect";
|
||||
flash_view.fields = {{"message", "Message", "text", "shown once on the next page"}};
|
||||
r.get("/flash/set", "flash-form", [this, flash_view](fw::Request) { return form_page(flash_view); });
|
||||
r.post("/flash/set", "flash-set", [this, flash_view](fw::Request req) {
|
||||
fw::Model model({{"message", fw::FieldType::String, true, 1, 120, 0, 0, false, ""}});
|
||||
std::map<std::string, std::string> clean;
|
||||
try {
|
||||
clean = fw::Form(model).bind(req);
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return invalid(flash_view, req, e);
|
||||
}
|
||||
std::string cookie = fw::make_set_cookie("flash", fw::FlashCodec::encode(clean["message"]),
|
||||
"/", true, false, "Lax", 60);
|
||||
fw::Response res = wants_html(req) ? see_other("/flash") : json("{\"ok\":true}");
|
||||
res.headers.set("Set-Cookie", cookie);
|
||||
return res;
|
||||
});
|
||||
r.get("/flash", "flash-show", [this](fw::Request req) {
|
||||
std::string msg;
|
||||
bool has = fw::FlashCodec::decode(req.cookie_or("flash", ""), msg);
|
||||
std::string body;
|
||||
if (has) body += "<p class=\"ok\" role=\"status\">" + esc(msg) + "</p>";
|
||||
else body += "<p class=\"hint\">No flash message. It is shown once after a POST.</p>";
|
||||
body += "<p><a href=\"/flash/set\">Set a message</a></p>";
|
||||
fw::Response res = page("Flash messages", body);
|
||||
if (has) res.headers.set("Set-Cookie", fw::make_set_cookie("flash", "", "/", true, false, "Lax", 0));
|
||||
return res;
|
||||
});
|
||||
|
||||
r.any({fw::Method::Get, fw::Method::Post}, "/middleware/demo", "middleware-demo",
|
||||
[this](fw::Request req) {
|
||||
std::vector<fw::Middleware> chain;
|
||||
chain.push_back([](fw::Request q, fw::Next next) { // secure headers
|
||||
fw::Response res = next(std::move(q));
|
||||
res.headers.set("X-Content-Type-Options", "nosniff");
|
||||
res.headers.set("X-Frame-Options", "DENY");
|
||||
res.headers.set("Referrer-Policy", "no-referrer");
|
||||
return res;
|
||||
});
|
||||
chain.push_back([](fw::Request q, fw::Next next) { // body limit
|
||||
if (q.body.size() > 64)
|
||||
return fw::Response(413, "{\"error\":\"too_large\",\"max\":64}", "application/json");
|
||||
return next(std::move(q));
|
||||
});
|
||||
chain.push_back([](fw::Request q, fw::Next next) { // timing
|
||||
auto t0 = std::chrono::steady_clock::now();
|
||||
fw::Response res = next(std::move(q));
|
||||
long us = (long)std::chrono::duration_cast<std::chrono::microseconds>(
|
||||
std::chrono::steady_clock::now() - t0).count();
|
||||
res.headers.set("X-Response-Time-Us", std::to_string(us));
|
||||
return res;
|
||||
});
|
||||
fw::Next end = [this](fw::Request q) {
|
||||
return page("Middleware builtins",
|
||||
"<p>This response passed through three builtin middlewares: secure headers, "
|
||||
"body limit (64 bytes) and timing. Inspect the response headers.</p>"
|
||||
"<p class=\"hint\">Received " + std::to_string(q.body.size()) + " body bytes.</p>");
|
||||
};
|
||||
for (std::size_t i = chain.size(); i > 0; --i) {
|
||||
fw::Middleware mw = chain[i - 1];
|
||||
fw::Next inner = end;
|
||||
end = [mw, inner](fw::Request q) { return mw(std::move(q), inner); };
|
||||
}
|
||||
return end(std::move(req));
|
||||
});
|
||||
|
||||
r.get("/cli/commands", "cli-commands", [this](fw::Request req) {
|
||||
static const std::vector<std::pair<std::string, std::string>> cmds = {
|
||||
{"new", "Scaffold a project (Makefile, AGENTS.md, .env.json, assets, templates, locales, git init)."},
|
||||
{"serve", "Dev server; --reload watches and rebuilds."},
|
||||
{"build", "Build, optionally embedding assets first."},
|
||||
{"embed", "Turn a static dir into constexpr C++ arrays, optionally gzip."},
|
||||
{"migrate", "Preview (--check) or apply (--apply) database migrations."},
|
||||
{"health", "Local liveness and readiness summary."},
|
||||
{"supervisor", "start, stop, restart, status, logs."},
|
||||
{"task", "enqueue, retry, cancel, inspect on the background queue."},
|
||||
{"ai", "new and continue: the AI agent."},
|
||||
{"expose", "serve, agent, list, stats, expose-key: reverse tunnels."},
|
||||
{"verify", "Offline artifact verification."},
|
||||
{"supply-check", "Pin and advisory gate."},
|
||||
{"release", "Ordered release gate."},
|
||||
{"rollout", "Staged deploys."},
|
||||
{"rollback", "Revert a rollout."},
|
||||
{"experiment", "Chaos and experiments."},
|
||||
{"debug", "Debug helpers."}};
|
||||
if (!wants_html(req)) {
|
||||
std::string out = "{\"commands\":[";
|
||||
for (std::size_t i = 0; i < cmds.size(); ++i)
|
||||
out += std::string(i ? "," : "") + "{\"name\":\"" + cmds[i].first + "\",\"summary\":\"" +
|
||||
fw::json_escape(cmds[i].second) + "\"}";
|
||||
return json(out + "]}");
|
||||
}
|
||||
std::string body = "<p class=\"hint\">Run <code>molo help <command></code> for full help.</p>"
|
||||
"<div class=\"scroll\"><table><thead><tr><th>Command</th><th>What it does</th>"
|
||||
"</tr></thead><tbody>";
|
||||
for (const auto& [n, s] : cmds)
|
||||
body += "<tr><td><code>molo " + n + "</code></td><td>" + esc(s) + "</td></tr>";
|
||||
body += "</tbody></table></div>";
|
||||
return page("molo commands", body);
|
||||
});
|
||||
}
|
||||
|
||||
void PlatformDemo::mount_expose(fw::Router& r) {
|
||||
FormView view;
|
||||
view.title = "Record a tunnel request";
|
||||
view.action = "/expose/record";
|
||||
view.submit = "Record";
|
||||
view.fields = {{"method", "Method", "text", "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS"},
|
||||
{"bytes_up", "Bytes up", "number", "0 to 1000000000"},
|
||||
{"bytes_down", "Bytes down", "number", "0 to 1000000000"},
|
||||
{"micros", "Latency (microseconds)", "number", "0 to 60000000"}};
|
||||
r.get("/expose/record", "expose-form", [this, view](fw::Request) { return form_page(view); });
|
||||
r.post("/expose/record", "expose-record", [this, view](fw::Request req) {
|
||||
fw::Model model(
|
||||
{{"method", fw::FieldType::String, true, 3, 7, 0, 0, false, ""},
|
||||
{"bytes_up", fw::FieldType::Integer, true, 0, 0, 0, 1000000000, true, ""},
|
||||
{"bytes_down", fw::FieldType::Integer, true, 0, 0, 0, 1000000000, true, ""},
|
||||
{"micros", fw::FieldType::Integer, true, 0, 0, 0, 60000000, true, ""}});
|
||||
std::map<std::string, std::string> c;
|
||||
try {
|
||||
c = fw::Form(model).bind(req);
|
||||
if (!fw::ExposeStats::known_method(c["method"]))
|
||||
throw fw::ValidationError({{"method", "must be an HTTP method in capitals"}});
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return invalid(view, req, e);
|
||||
}
|
||||
expose_.record(c["method"], std::stoul(c["bytes_up"]), std::stoul(c["bytes_down"]),
|
||||
std::stoul(c["micros"]));
|
||||
if (!wants_html(req)) return json("{\"ok\":true}");
|
||||
return see_other("/expose/stats");
|
||||
});
|
||||
r.get("/expose/stats", "expose-stats", [this](fw::Request req) {
|
||||
auto snap = expose_.snapshot();
|
||||
auto kb = [](unsigned long b) { char x[32]; std::snprintf(x, sizeof x, "%.1f", b / 1024.0); return std::string(x); };
|
||||
auto f2 = [](double v) { char x[32]; std::snprintf(x, sizeof x, "%.2f", v); return std::string(x); };
|
||||
if (!wants_html(req)) {
|
||||
std::string out = "{\"methods\":{";
|
||||
bool first = true;
|
||||
for (const auto& [m, row] : snap) {
|
||||
out += std::string(first ? "" : ",") + "\"" + m + "\":{\"count\":" + std::to_string(row.count) +
|
||||
",\"kb_up\":" + kb(row.bytes_up) + ",\"kb_down\":" + kb(row.bytes_down) +
|
||||
",\"kb_s_up\":" + f2(row.kb_s_up) + ",\"kb_s_down\":" + f2(row.kb_s_down) +
|
||||
",\"avg_ms\":" + f2(row.avg_ms()) + "}";
|
||||
first = false;
|
||||
}
|
||||
return json(out + "}}");
|
||||
}
|
||||
std::string body = "<p class=\"hint\">Mirror of <code>molo expose stats</code>. Rates are a "
|
||||
"60 second window. <a href=\"/expose/record\">Record a request</a>.</p>"
|
||||
"<div class=\"scroll\"><table><thead><tr><th>Method</th><th>Count</th>"
|
||||
"<th>kB up</th><th>kB down</th><th>kB/s up</th><th>kB/s down</th>"
|
||||
"<th>Avg ms</th></tr></thead><tbody>";
|
||||
for (const auto& [m, row] : snap)
|
||||
body += "<tr><td>" + m + "</td><td>" + std::to_string(row.count) + "</td><td>" + kb(row.bytes_up) +
|
||||
"</td><td>" + kb(row.bytes_down) + "</td><td>" + f2(row.kb_s_up) + "</td><td>" +
|
||||
f2(row.kb_s_down) + "</td><td>" + f2(row.avg_ms()) + "</td></tr>";
|
||||
body += "</tbody></table></div>";
|
||||
return page("Expose stats", body);
|
||||
});
|
||||
}
|
||||
|
||||
void PlatformDemo::mount(fw::Router& r) {
|
||||
mount_i18n(r);
|
||||
mount_http(r);
|
||||
mount_ops(r);
|
||||
mount_observability(r);
|
||||
mount_app(r);
|
||||
mount_expose(r);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_platform_demo(fw::Router& router, Services& services) {
|
||||
auto demo = std::make_shared<PlatformDemo>(services);
|
||||
// Routes capture the raw pointer; the router owner keeps `demo` alive by
|
||||
// holding it in a static-lifetime registry below (bounded: one per app).
|
||||
static std::vector<std::shared_ptr<PlatformDemo>> keep;
|
||||
if (keep.size() >= 64) throw std::runtime_error("platform demo instance cap");
|
||||
keep.push_back(demo);
|
||||
demo->mount(router);
|
||||
|
||||
services.add_feature("i18n", "/i18n");
|
||||
services.add_feature("gzip compression", "/compress/demo");
|
||||
services.add_feature("conditional GET and ranges", "/conditional/doc");
|
||||
services.add_feature("liveness probe", "/healthz");
|
||||
services.add_feature("readiness probe", "/readyz");
|
||||
services.add_feature("startup gate", "/startupz");
|
||||
services.add_feature("prometheus metrics", "/metrics");
|
||||
services.add_feature("structured logging", "/logging/records");
|
||||
services.add_feature("trace context", "/context/trace");
|
||||
services.add_feature("DI container", "/di/services");
|
||||
services.add_feature("flash messages", "/flash");
|
||||
services.add_feature("middleware builtins", "/middleware/demo");
|
||||
services.add_feature("expose stats", "/expose/stats");
|
||||
services.add_feature("CLI commands", "/cli/commands");
|
||||
}
|
||||
|
||||
} // namespace molo::example::app
|
||||
@@ -70,6 +70,11 @@ void register_realtime_demo(fw::Router& router, Services& services) {
|
||||
return fw::Response(207, webdav->propfind_xml("/files/"),
|
||||
"application/xml");
|
||||
});
|
||||
router.get("/webdav/files/", "webdav-index", [webdav](fw::Request req) {
|
||||
(void)req;
|
||||
return fw::Response(200, webdav->propfind_xml("/files/"),
|
||||
"application/xml");
|
||||
});
|
||||
router.any({fw::Method::Get}, "/webdav/files/{name}", "webdav-get",
|
||||
[webdav](fw::Request req) -> fw::Response {
|
||||
std::string content;
|
||||
|
||||
@@ -0,0 +1,621 @@
|
||||
#include "App.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "../fw/Resilience.hpp"
|
||||
#include "../fw/Router.hpp"
|
||||
#include "../fw/Templates.hpp"
|
||||
#include "../fw/Validate.hpp"
|
||||
#include "FormUi.hpp"
|
||||
|
||||
// Interactive lab pages for operability, supply chain, clients and data depth.
|
||||
// Each page is a LabPage: a GET that renders the lab state plus one POST route
|
||||
// per button. HTML clients get the page back, JSON clients get the lab state;
|
||||
// validation failures render the shared inline-error form (422).
|
||||
|
||||
namespace molo::example::app {
|
||||
|
||||
namespace {
|
||||
|
||||
using Params = std::map<std::string, std::string>;
|
||||
|
||||
const char kLabPage[] = R"LAB({% extends "base.html" %}
|
||||
{% block content %}
|
||||
<h1>{{ title }}</h1>
|
||||
<p class="hint">{{ intro }}</p>
|
||||
{% if notice %}<p class="ok" role="status">{{ notice }}</p>{% endif %}
|
||||
<div class="scroll"><table>
|
||||
<thead><tr><th>State</th><th>Value</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in rows %}
|
||||
<tr><td>{{ r.k }}</td><td>{{ r.v }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table></div>
|
||||
{% for a in actions %}
|
||||
{{ a.html|safe }}
|
||||
{% endfor %}
|
||||
<h2>Log</h2>
|
||||
<ul>
|
||||
{% for l in log %}
|
||||
<li>{{ l.line }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endblock %}
|
||||
)LAB";
|
||||
|
||||
// Throws the standard field error when `value` is not one of `allowed`.
|
||||
void require_in(const std::string& field, const std::string& value,
|
||||
const std::vector<std::string>& allowed) {
|
||||
if (std::find(allowed.begin(), allowed.end(), value) != allowed.end()) return;
|
||||
std::string list;
|
||||
for (const auto& a : allowed) list += (list.empty() ? "" : ", ") + a;
|
||||
throw fw::ValidationError({{field, "must be one of: " + list}});
|
||||
}
|
||||
|
||||
// One button (with its inputs) on a lab page and the handler behind it.
|
||||
class ActionSpec {
|
||||
public:
|
||||
ActionSpec(std::string sub, std::string label)
|
||||
: sub_(std::move(sub)), label_(std::move(label)) {}
|
||||
|
||||
ActionSpec& num(const std::string& name, const std::string& label, long lo,
|
||||
long hi, const std::string& def, const std::string& hint = "") {
|
||||
model_.push_back({name, fw::FieldType::Integer, false, 0, 1024, lo, hi,
|
||||
true, def});
|
||||
form_.push_back({name, label, "number",
|
||||
hint.empty() ? std::to_string(lo) + " to " + std::to_string(hi)
|
||||
: hint});
|
||||
defaults_[name] = def;
|
||||
return *this;
|
||||
}
|
||||
ActionSpec& text(const std::string& name, const std::string& label,
|
||||
std::size_t min, std::size_t max, const std::string& def,
|
||||
const std::string& hint = "", bool required = true) {
|
||||
model_.push_back({name, fw::FieldType::String, required, min, max, 0, 0,
|
||||
false, required ? "" : def});
|
||||
form_.push_back({name, label, "text", hint});
|
||||
defaults_[name] = def;
|
||||
return *this;
|
||||
}
|
||||
ActionSpec& run(std::function<std::string(const Params&)> fn) {
|
||||
run_ = std::move(fn);
|
||||
return *this;
|
||||
}
|
||||
ActionSpec& dynamic_defaults(std::function<Params()> fn) {
|
||||
dyn_ = std::move(fn);
|
||||
return *this;
|
||||
}
|
||||
|
||||
const std::string& sub() const { return sub_; }
|
||||
const std::string& label() const { return label_; }
|
||||
const std::vector<FormField>& form() const { return form_; }
|
||||
fw::Model model() const { return fw::Model(model_); }
|
||||
Params defaults() const {
|
||||
Params d = defaults_;
|
||||
if (dyn_)
|
||||
for (const auto& [k, v] : dyn_()) d[k] = v;
|
||||
return d;
|
||||
}
|
||||
std::string execute(const Params& p) const { return run_ ? run_(p) : ""; }
|
||||
|
||||
private:
|
||||
std::string sub_, label_;
|
||||
std::vector<fw::Field> model_;
|
||||
std::vector<FormField> form_;
|
||||
Params defaults_;
|
||||
std::function<Params()> dyn_;
|
||||
std::function<std::string(const Params&)> run_;
|
||||
};
|
||||
|
||||
class LabPage {
|
||||
public:
|
||||
LabPage(fw::Environment* env, std::string path, std::string title,
|
||||
std::string intro, std::shared_ptr<fw::Lab> lab)
|
||||
: env_(env),
|
||||
path_(std::move(path)),
|
||||
title_(std::move(title)),
|
||||
intro_(std::move(intro)),
|
||||
lab_(std::move(lab)) {}
|
||||
|
||||
ActionSpec& action(std::string sub, std::string label) {
|
||||
actions_.emplace_back(std::move(sub), std::move(label));
|
||||
return actions_.back();
|
||||
}
|
||||
void extra_rows(std::function<fw::LabRows()> fn) { extra_ = std::move(fn); }
|
||||
|
||||
fw::Response page(int status, const std::string& notice) const {
|
||||
fw::TemplateCtx ctx;
|
||||
ctx["title"] = title_;
|
||||
ctx["intro"] = intro_;
|
||||
ctx["notice"] = notice;
|
||||
fw::TemplateList rows, acts, log;
|
||||
fw::LabRows all = lab_->rows();
|
||||
if (extra_)
|
||||
for (auto& r : extra_()) all.push_back(std::move(r));
|
||||
for (const auto& [k, v] : all) rows.push_back({{"k", k}, {"v", v}});
|
||||
for (const auto& a : actions_) acts.push_back({{"html", action_html(a)}});
|
||||
for (const auto& l : lab_->log()) log.push_back({{"line", l}});
|
||||
ctx["rows"] = rows;
|
||||
ctx["actions"] = acts;
|
||||
ctx["log"] = log;
|
||||
return fw::Response(status, env_->render("lab_page.html", ctx),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
fw::Response invalid(const ActionSpec& a, const fw::Request& req,
|
||||
const fw::ValidationError& e) const {
|
||||
if (!wants_html(req)) return fw::JsonResponse(e.to_json(), 422);
|
||||
FormView v;
|
||||
v.title = a.label();
|
||||
v.action = path_ + a.sub();
|
||||
v.submit = a.label();
|
||||
v.fields = a.form();
|
||||
v.values = a.defaults();
|
||||
for (const auto& [k, val] : fw::parse_form(req.body)) v.values[k] = val;
|
||||
v.error = &e;
|
||||
return fw::Response(422, env_->render("form_page.html", v.ctx()),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
fw::Response handle(std::size_t i, const fw::Request& req) const {
|
||||
const ActionSpec& a = actions_[i];
|
||||
std::string notice;
|
||||
try {
|
||||
notice = a.execute(fw::Form(a.model()).bind(req));
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return invalid(a, req, e);
|
||||
}
|
||||
if (!wants_html(req)) return fw::JsonResponse(lab_->json(), 200);
|
||||
return page(200, notice);
|
||||
}
|
||||
|
||||
void mount(fw::Router& router, const std::shared_ptr<LabPage>& self,
|
||||
const std::string& name) {
|
||||
router.get(path_, name, [self](fw::Request) { return self->page(200, ""); });
|
||||
for (std::size_t i = 0; i < actions_.size(); ++i)
|
||||
router.post(path_ + actions_[i].sub(), name + actions_[i].sub(),
|
||||
[self, i](fw::Request req) { return self->handle(i, req); });
|
||||
}
|
||||
|
||||
private:
|
||||
std::string action_html(const ActionSpec& a) const {
|
||||
std::string h = "<form method=\"post\" class=\"toolbar\" action=\"" +
|
||||
fw::html_escape(path_ + a.sub()) + "\">";
|
||||
Params d = a.defaults();
|
||||
for (const auto& f : a.form()) {
|
||||
h += "<label class=\"inline\">" + fw::html_escape(f.label) +
|
||||
" <input type=\"" + f.type + "\" name=\"" + fw::html_escape(f.name) +
|
||||
"\" value=\"" + fw::html_escape(d[f.name]) +
|
||||
"\" style=\"max-width:9rem\" title=\"" + fw::html_escape(f.hint) +
|
||||
"\"></label>";
|
||||
}
|
||||
return h + "<button type=\"submit\">" + fw::html_escape(a.label()) +
|
||||
"</button></form>";
|
||||
}
|
||||
|
||||
fw::Environment* env_;
|
||||
std::string path_, title_, intro_;
|
||||
std::shared_ptr<fw::Lab> lab_;
|
||||
std::deque<ActionSpec> actions_; // deque: stable references while adding
|
||||
std::function<fw::LabRows()> extra_;
|
||||
};
|
||||
|
||||
long to_long(const Params& p, const std::string& k) {
|
||||
return std::stol(p.at(k));
|
||||
}
|
||||
|
||||
// Builds, wires and registers one lab page in the index matrix.
|
||||
class Mounter {
|
||||
public:
|
||||
Mounter(fw::Router& router, Services& services,
|
||||
std::shared_ptr<fw::DebugRegistry> registry)
|
||||
: router_(router), services_(services), registry_(std::move(registry)) {}
|
||||
|
||||
std::shared_ptr<LabPage> page(const std::string& feature,
|
||||
const std::string& path,
|
||||
const std::string& title,
|
||||
const std::string& intro,
|
||||
std::shared_ptr<fw::Lab> lab) {
|
||||
auto p = std::make_shared<LabPage>(services_.templates.get(), path, title,
|
||||
intro, std::move(lab));
|
||||
pending_.push_back({p, feature, path});
|
||||
return p;
|
||||
}
|
||||
void finish() {
|
||||
for (auto& e : pending_) {
|
||||
e.page->mount(router_, e.page, e.path);
|
||||
services_.add_feature(e.feature, e.path);
|
||||
}
|
||||
pending_.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
std::shared_ptr<LabPage> page;
|
||||
std::string feature, path;
|
||||
};
|
||||
fw::Router& router_;
|
||||
Services& services_;
|
||||
std::shared_ptr<fw::DebugRegistry> registry_;
|
||||
std::vector<Entry> pending_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_resilience_demo(fw::Router& router, Services& services) {
|
||||
services.templates->add_template("lab_page.html", kLabPage);
|
||||
auto registry = std::make_shared<fw::DebugRegistry>();
|
||||
Mounter m(router, services, registry);
|
||||
|
||||
// ---- operability: resilience -------------------------------------------
|
||||
auto bclock = std::make_shared<fw::ManualClock>();
|
||||
auto breaker = std::make_shared<fw::CircuitBreaker>(bclock);
|
||||
registry->add(breaker);
|
||||
auto p = m.page("Circuit breaker", "/operability/breaker", "Circuit breaker",
|
||||
"Three failures open the breaker, calls are rejected while "
|
||||
"open, 30 s of injected clock time later it goes half-open "
|
||||
"and one good call closes it again.",
|
||||
breaker);
|
||||
p->action("/success", "Call succeeds").run([breaker](const Params&) {
|
||||
return breaker->call(true) ? "call recorded" : "rejected: breaker open";
|
||||
});
|
||||
p->action("/failure", "Call fails").run([breaker](const Params&) {
|
||||
return breaker->call(false) ? "failure recorded" : "rejected: breaker open";
|
||||
});
|
||||
p->action("/tick", "Advance 10 s").run([breaker](const Params&) {
|
||||
breaker->tick(10000);
|
||||
return "clock advanced 10 s";
|
||||
});
|
||||
|
||||
auto bulkhead = std::make_shared<fw::Bulkhead>();
|
||||
registry->add(bulkhead);
|
||||
p = m.page("Bulkhead", "/operability/bulkhead", "Bulkhead",
|
||||
"Two concurrent slots and a queue of one; the fourth caller is "
|
||||
"rejected instead of starving the rest.",
|
||||
bulkhead);
|
||||
p->action("/acquire", "Take a slot").run([bulkhead](const Params&) {
|
||||
switch (bulkhead->acquire()) {
|
||||
case fw::Bulkhead::Admission::Admitted: return "admitted";
|
||||
case fw::Bulkhead::Admission::Queued: return "queued";
|
||||
default: return "rejected: compartment full";
|
||||
}
|
||||
});
|
||||
p->action("/release", "Release a slot").run([bulkhead](const Params&) {
|
||||
return bulkhead->release() ? "released" : "nothing to release";
|
||||
});
|
||||
|
||||
auto shedder = std::make_shared<fw::Shedder>();
|
||||
registry->add(shedder);
|
||||
p = m.page("Load shedder", "/operability/shedder", "Load shedder",
|
||||
"Limit 3 in flight. Low priority work is shed first (at 2), high "
|
||||
"priority only at the limit.",
|
||||
shedder);
|
||||
p->action("/enter", "Start request")
|
||||
.text("priority", "Priority", 1, 8, "low", "low or high", false)
|
||||
.run([shedder](const Params& q) {
|
||||
require_in("priority", q.at("priority"), {"low", "high"});
|
||||
return shedder->enter(q.at("priority") == "high") ? "accepted" : "shed";
|
||||
});
|
||||
p->action("/leave", "Finish request").run([shedder](const Params&) {
|
||||
return shedder->leave() ? "finished" : "nothing in flight";
|
||||
});
|
||||
|
||||
auto deadline = std::make_shared<fw::DeadlineLab>();
|
||||
registry->add(deadline);
|
||||
p = m.page("Deadline propagation", "/operability/deadline",
|
||||
"Deadline propagation",
|
||||
"One budget travels through every hop; each hop costs 30 ms and a "
|
||||
"hop that cannot finish in time is skipped.",
|
||||
deadline);
|
||||
p->action("/run", "Run chain")
|
||||
.num("budget_ms", "Budget ms", 0, 5000, "100")
|
||||
.num("hops", "Hops", 1, 10, "3")
|
||||
.run([deadline](const Params& q) {
|
||||
int hop = deadline->run(to_long(q, "budget_ms"), (int)to_long(q, "hops"));
|
||||
return hop ? "deadline exceeded at hop " + std::to_string(hop)
|
||||
: std::string("all hops finished in budget");
|
||||
});
|
||||
|
||||
auto slo = std::make_shared<fw::SloBudget>();
|
||||
registry->add(slo);
|
||||
p = m.page("SLO error budget", "/operability/slo", "SLO error budget",
|
||||
"95.0% target over the last 100 events. The error budget is how "
|
||||
"many bad events the window still allows.",
|
||||
slo);
|
||||
p->action("/good", "Good event").run([slo](const Params&) {
|
||||
slo->record(true);
|
||||
return "good event recorded";
|
||||
});
|
||||
p->action("/bad", "Bad event").run([slo](const Params&) {
|
||||
slo->record(false);
|
||||
return "bad event recorded";
|
||||
});
|
||||
p->action("/reset", "Reset window").run([slo](const Params&) {
|
||||
slo->reset();
|
||||
return "window reset";
|
||||
});
|
||||
|
||||
// ---- operability: chaos, deploy, coordination ---------------------------
|
||||
auto chaos = std::make_shared<fw::ChaosLab>();
|
||||
registry->add(chaos);
|
||||
p = m.page("Chaos experiment", "/operability/chaos", "Chaos experiment",
|
||||
"Fault injection with a hard blast radius: at most 50 percent and "
|
||||
"5 faults over 10 calls. Armed 0 is a dry run and injects nothing.",
|
||||
chaos);
|
||||
p->action("/run", "Run experiment")
|
||||
.num("percent", "Percent", 0, fw::labcaps::kMaxPercent, "20")
|
||||
.num("max_faults", "Max faults", 1, fw::labcaps::kMaxFaults, "2")
|
||||
.num("armed", "Armed", 0, 1, "0", "0 dry run, 1 armed")
|
||||
.run([chaos](const Params& q) {
|
||||
auto r = chaos->run((int)to_long(q, "percent"),
|
||||
(int)to_long(q, "max_faults"), to_long(q, "armed") == 1);
|
||||
return std::string(r.armed ? "armed: " : "dry run: ") +
|
||||
std::to_string(r.injected) + " injected, " +
|
||||
std::to_string(r.planned) + " planned";
|
||||
});
|
||||
|
||||
auto deploy = std::make_shared<fw::DeployLab>();
|
||||
registry->add(deploy);
|
||||
p = m.page("Deploy strategies", "/operability/deploy", "Deploy strategies",
|
||||
"Rolling replaces one instance per step; blue-green prepares a "
|
||||
"green fleet and switches in one step. Rollback restores the "
|
||||
"previous fleet.",
|
||||
deploy);
|
||||
p->action("/start", "Start rollout")
|
||||
.text("strategy", "Strategy", 1, 16, "rolling", "rolling or bluegreen", false)
|
||||
.text("version", "Version", 1, 16, "v2", "", false)
|
||||
.run([deploy](const Params& q) {
|
||||
require_in("strategy", q.at("strategy"), {"rolling", "bluegreen"});
|
||||
return deploy->start(q.at("strategy"), q.at("version"))
|
||||
? "rollout started"
|
||||
: "a rollout is already in progress";
|
||||
});
|
||||
p->action("/step", "Next step").run([deploy](const Params&) {
|
||||
return deploy->step() ? "step done" : "no rollout in progress";
|
||||
});
|
||||
p->action("/rollback", "Roll back").run([deploy](const Params&) {
|
||||
return deploy->rollback() ? "rolled back" : "nothing to roll back";
|
||||
});
|
||||
|
||||
auto cclock = std::make_shared<fw::ManualClock>();
|
||||
auto coord = std::make_shared<fw::CoordLab>(cclock);
|
||||
registry->add(coord);
|
||||
p = m.page("Lease, election, fenced lock", "/operability/coord",
|
||||
"Coordination",
|
||||
"Lease, leader election and distributed lock share one rule: a "
|
||||
"new holder gets a higher fencing token, and writes with a stale "
|
||||
"token are rejected. Leases last 10 s of injected time.",
|
||||
coord);
|
||||
p->action("/acquire", "Acquire")
|
||||
.text("key", "Key", 1, 16, "lock", "lease, lock or leader", false)
|
||||
.text("owner", "Owner", 1, 32, "a", "", true)
|
||||
.run([coord](const Params& q) {
|
||||
require_in("key", q.at("key"), {"lease", "lock", "leader"});
|
||||
auto g = coord->acquire(q.at("key"), q.at("owner"));
|
||||
return g.ok ? "granted token " + std::to_string(g.token)
|
||||
: "denied, held by " + g.holder;
|
||||
});
|
||||
p->action("/release", "Release")
|
||||
.text("key", "Key", 1, 16, "lock", "lease, lock or leader", false)
|
||||
.text("owner", "Owner", 1, 32, "a", "", true)
|
||||
.run([coord](const Params& q) {
|
||||
require_in("key", q.at("key"), {"lease", "lock", "leader"});
|
||||
return coord->release(q.at("key"), q.at("owner")) ? "released"
|
||||
: "not the holder";
|
||||
});
|
||||
p->action("/write", "Fenced write")
|
||||
.text("key", "Key", 1, 16, "lock", "lease, lock or leader", false)
|
||||
.num("token", "Token", 0, 1000000, "1")
|
||||
.run([coord](const Params& q) {
|
||||
require_in("key", q.at("key"), {"lease", "lock", "leader"});
|
||||
return coord->write(q.at("key"), to_long(q, "token"))
|
||||
? "write accepted"
|
||||
: "write rejected: stale fencing token";
|
||||
});
|
||||
p->action("/tick", "Advance 6 s").run([coord](const Params&) {
|
||||
coord->tick(6000);
|
||||
return "clock advanced 6 s";
|
||||
});
|
||||
|
||||
// ---- supply chain -------------------------------------------------------
|
||||
auto supply = std::make_shared<fw::SupplyChainLab>();
|
||||
registry->add(supply);
|
||||
p = m.page("Supply chain gate", "/supplychain", "Supply chain gate",
|
||||
"Illustrative SBOM of this example (CycloneDX shape), dependency "
|
||||
"pins, an advisory scan and an attestation check. The gate passes "
|
||||
"only when all three pass. The digest is FNV-1a, not a signature.",
|
||||
supply);
|
||||
p->action("/advisory", "Publish advisory for chartjs 4.4.1")
|
||||
.run([supply](const Params&) {
|
||||
return supply->add_advisory("chartjs", "4.4.1") ? "advisory published"
|
||||
: "advisory db full";
|
||||
});
|
||||
p->action("/tamper", "Tamper with chartjs").run([supply](const Params&) {
|
||||
supply->tamper();
|
||||
return "component changed after attestation";
|
||||
});
|
||||
p->action("/verify", "Verify attestation")
|
||||
.text("digest", "Digest", 16, 16, "", "16 hex characters of sbom_digest")
|
||||
.dynamic_defaults([supply] { return Params{{"digest", supply->attested()}}; })
|
||||
.run([supply](const Params& q) {
|
||||
return supply->verify(q.at("digest")) ? "attestation verified"
|
||||
: "attestation FAILED";
|
||||
});
|
||||
p->action("/reset", "Regenerate and attest").run([supply](const Params&) {
|
||||
supply->reset();
|
||||
return "sbom regenerated";
|
||||
});
|
||||
router.get("/supplychain/sbom.json", "supplychain-sbom",
|
||||
[supply](fw::Request) {
|
||||
return fw::JsonResponse(supply->cyclonedx(), 200);
|
||||
});
|
||||
|
||||
// ---- clients depth ------------------------------------------------------
|
||||
auto retry = std::make_shared<fw::ClientRetryLab>();
|
||||
registry->add(retry);
|
||||
p = m.page("Client retry and backoff", "/clients/retry",
|
||||
"Client retry and backoff",
|
||||
"In-process transport that fails the first N calls. 5xx is "
|
||||
"retried with doubling backoff capped at 800 ms and at most 5 "
|
||||
"attempts; 4xx is never retried. Waits are virtual.",
|
||||
retry);
|
||||
p->action("/run", "Send request")
|
||||
.num("failures", "Failures", 0, 10, "2")
|
||||
.num("max_attempts", "Max attempts", 1, fw::labcaps::kMaxAttempts, "3")
|
||||
.num("status", "Failure status", 400, 599, "503")
|
||||
.run([retry](const Params& q) {
|
||||
auto o = retry->run((int)to_long(q, "failures"),
|
||||
(int)to_long(q, "max_attempts"),
|
||||
(int)to_long(q, "status"));
|
||||
return "final status " + std::to_string(o.status) + " after " +
|
||||
std::to_string(o.attempts) + " attempt(s)";
|
||||
});
|
||||
|
||||
auto session = std::make_shared<fw::ClientSessionLab>();
|
||||
registry->add(session);
|
||||
p = m.page("Client session: cookies, pool, proxy, auth", "/clients/session",
|
||||
"Client session",
|
||||
"Each request goes through the in-process transport: the server "
|
||||
"sets cookies into the jar, connections are pooled and reused, a "
|
||||
"proxy change opens a new connection, and the auth scheme sets the "
|
||||
"Authorization header.",
|
||||
session);
|
||||
p->action("/request", "Send request")
|
||||
.text("auth", "Auth", 1, 8, "none", "none, basic or bearer", false)
|
||||
.text("proxy", "Proxy", 0, 80, "", "http://host:port or empty", false)
|
||||
.run([session](const Params& q) {
|
||||
require_in("auth", q.at("auth"), {"none", "basic", "bearer"});
|
||||
auto px = q.count("proxy") ? q.at("proxy") : std::string();
|
||||
if (!fw::ClientSessionLab::valid_proxy(px))
|
||||
throw fw::ValidationError(
|
||||
{{"proxy", "must be empty or http(s)/socks5://host:port"}});
|
||||
auto h = session->request(q.at("auth"), px);
|
||||
std::string out = "sent:";
|
||||
for (const auto& [k, v] : h) out += " " + k + "=" + v + ";";
|
||||
return out;
|
||||
});
|
||||
|
||||
// ---- data depth ---------------------------------------------------------
|
||||
auto mig = std::make_shared<fw::MigrationLab>();
|
||||
registry->add(mig);
|
||||
p = m.page("Migrations: check then apply", "/data/migrations",
|
||||
"Migrations",
|
||||
"Preview shows what apply would run without changing anything. "
|
||||
"Apply runs pending steps in order. Drift drops a table out of "
|
||||
"band and heal re-creates it from its migration.",
|
||||
mig);
|
||||
p->extra_rows([mig] {
|
||||
fw::LabRows r;
|
||||
for (const auto& line : mig->check()) r.emplace_back("preview", line);
|
||||
return r;
|
||||
});
|
||||
p->action("/apply", "Apply")
|
||||
.num("limit", "Steps", 1, 3, "3")
|
||||
.run([mig](const Params& q) {
|
||||
int n = mig->apply((int)to_long(q, "limit"));
|
||||
return std::to_string(n) + " migration(s) applied";
|
||||
});
|
||||
p->action("/drift", "Drop posts table").run([mig](const Params&) {
|
||||
mig->drop_table("posts");
|
||||
return "posts dropped out of band";
|
||||
});
|
||||
p->action("/heal", "Heal drift").run([mig](const Params&) {
|
||||
return std::to_string(mig->heal()) + " table(s) healed";
|
||||
});
|
||||
|
||||
auto tx = std::make_shared<fw::TxLab>();
|
||||
registry->add(tx);
|
||||
p = m.page("Transaction rollback", "/data/transaction", "Transaction rollback",
|
||||
"Transfer between alice and bob inside a transaction. Overdrafts "
|
||||
"and a failure after the debit roll back, so no money is lost.",
|
||||
tx);
|
||||
p->action("/transfer", "Transfer")
|
||||
.text("from", "From", 1, 8, "alice", "alice or bob", false)
|
||||
.text("to", "To", 1, 8, "bob", "alice or bob", false)
|
||||
.num("amount", "Amount", 1, 1000, "30")
|
||||
.num("fail_after_debit", "Fail after debit", 0, 1, "0", "0 or 1")
|
||||
.run([tx](const Params& q) {
|
||||
require_in("from", q.at("from"), {"alice", "bob"});
|
||||
require_in("to", q.at("to"), {"alice", "bob"});
|
||||
if (q.at("from") == q.at("to"))
|
||||
throw fw::ValidationError({{"to", "must differ from the source"}});
|
||||
return tx->transfer(q.at("from"), q.at("to"), to_long(q, "amount"),
|
||||
to_long(q, "fail_after_debit") == 1);
|
||||
});
|
||||
|
||||
auto query = std::make_shared<fw::QueryLab>();
|
||||
registry->add(query);
|
||||
p = m.page("Query builder and relations", "/data/query",
|
||||
"Query builder and relations",
|
||||
"Builds a joined SELECT over users has-many posts and runs it on "
|
||||
"in-memory tables. User 0 means all users.",
|
||||
query);
|
||||
p->action("/run", "Run query")
|
||||
.num("user_id", "User id", 0, 2, "0")
|
||||
.text("order", "Order", 1, 8, "id", "id or title", false)
|
||||
.num("limit", "Limit", 1, 10, "5")
|
||||
.run([query](const Params& q) {
|
||||
require_in("order", q.at("order"), {"id", "title"});
|
||||
auto r = query->run(to_long(q, "user_id"), q.at("order"),
|
||||
(int)to_long(q, "limit"));
|
||||
return std::to_string(r.rows.size()) + " row(s)";
|
||||
});
|
||||
|
||||
auto flight = std::make_shared<fw::SingleFlightLab>();
|
||||
registry->add(flight);
|
||||
p = m.page("Singleflight", "/data/singleflight", "Singleflight",
|
||||
"Concurrent callers asking for the same key share one load. The "
|
||||
"loader waits for the other callers to join, so the result is "
|
||||
"deterministic. At most 16 threads.",
|
||||
flight);
|
||||
p->action("/run", "Run callers")
|
||||
.num("callers", "Callers", 1, fw::labcaps::kMaxThreads, "8")
|
||||
.run([flight](const Params& q) {
|
||||
int callers = (int)to_long(q, "callers");
|
||||
int loads = flight->run(callers);
|
||||
return std::to_string(callers) + " callers, " + std::to_string(loads) +
|
||||
" load(s)";
|
||||
});
|
||||
|
||||
auto tclock = std::make_shared<fw::ManualClock>();
|
||||
auto ttl = std::make_shared<fw::TtlLab>(tclock);
|
||||
registry->add(ttl);
|
||||
p = m.page("TTL store, LRU, pubsub", "/data/ttl", "TTL store",
|
||||
"Memory store with per-key TTL on injected time, LRU eviction at "
|
||||
"5 entries, and a pubsub topic kv.events announcing every change.",
|
||||
ttl);
|
||||
p->extra_rows([ttl] {
|
||||
fw::LabRows r;
|
||||
for (const auto& e : ttl->events()) r.emplace_back("event", e);
|
||||
return r;
|
||||
});
|
||||
p->action("/set", "Set key")
|
||||
.text("key", "Key", 1, 16, "", "", true)
|
||||
.text("value", "Value", 1, 32, "", "", true)
|
||||
.num("ttl_s", "TTL s", 1, 60, "10")
|
||||
.run([ttl](const Params& q) {
|
||||
ttl->set(q.at("key"), q.at("value"), to_long(q, "ttl_s"));
|
||||
return "stored " + q.at("key");
|
||||
});
|
||||
p->action("/get", "Get key")
|
||||
.text("key", "Key", 1, 16, "", "", true)
|
||||
.run([ttl](const Params& q) {
|
||||
std::string v;
|
||||
return ttl->get(q.at("key"), v) ? "hit: " + v : std::string("miss");
|
||||
});
|
||||
p->action("/tick", "Advance 5 s").run([ttl](const Params&) {
|
||||
ttl->tick(5000);
|
||||
return "clock advanced 5 s";
|
||||
});
|
||||
|
||||
m.finish();
|
||||
|
||||
router.get("/operability/debug", "operability-debug",
|
||||
[registry](fw::Request) {
|
||||
return fw::JsonResponse(registry->snapshot(), 200);
|
||||
});
|
||||
services.add_feature("Debug snapshot", "/operability/debug");
|
||||
}
|
||||
|
||||
} // namespace molo::example::app
|
||||
@@ -69,6 +69,20 @@ void register_security_demo(fw::Router& router, Services& services) {
|
||||
return res;
|
||||
});
|
||||
|
||||
router.get("/uploads/file", "upload-list", [uploads](fw::Request req) {
|
||||
(void)req;
|
||||
std::string body = "{\"files\":[";
|
||||
bool first = true;
|
||||
for (const auto& u : uploads->list()) {
|
||||
body += std::string(first ? "" : ",") + "{\"file\":\"" +
|
||||
fw::json_escape(u.filename) + "\",\"size\":" +
|
||||
std::to_string(u.size) + "}";
|
||||
first = false;
|
||||
}
|
||||
return fw::JsonResponse(
|
||||
body + "],\"usage\":\"POST body to /uploads/file?filename=<name>\"}",
|
||||
200);
|
||||
});
|
||||
router.post("/uploads/file", "upload", [uploads](fw::Request req) {
|
||||
std::string filename = req.query_or("filename", "upload.txt");
|
||||
std::string content_type =
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
#include "App.hpp"
|
||||
|
||||
#include "FormUi.hpp"
|
||||
#include "../fw/Cookies.hpp"
|
||||
#include "../fw/Router.hpp"
|
||||
#include "../fw/SecurityExtra.hpp"
|
||||
#include "../fw/Validate.hpp"
|
||||
|
||||
namespace molo::example::app {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr const char* kHtml = "text/html; charset=utf-8";
|
||||
|
||||
// Shared state of this group, owned by the closures through shared_ptr.
|
||||
struct SecState {
|
||||
fw::DenialSink denials;
|
||||
fw::CsrfGuard csrf;
|
||||
fw::CorsPolicy cors;
|
||||
fw::RateLimiter limiter;
|
||||
fw::CspReportStore csp_reports;
|
||||
fw::PermissionGuard perms;
|
||||
fw::SecretsProvider secrets;
|
||||
explicit SecState(const std::string& secret)
|
||||
: csrf(secret),
|
||||
cors({"https://app.example.com", "https://admin.example.com"}),
|
||||
limiter(5, 60) {}
|
||||
};
|
||||
|
||||
// One place that renders a FormView and maps failures to HTML or JSON.
|
||||
class FormPage {
|
||||
public:
|
||||
FormPage(fw::Environment* env, SecState* st) : env_(env), st_(st) {}
|
||||
|
||||
fw::Response show(const FormView& v, int status = 200) const {
|
||||
return fw::Response(status, env_->render("form_page.html", v.ctx()), kHtml);
|
||||
}
|
||||
fw::Response fail(FormView v, const fw::Request& req, const std::string& guard,
|
||||
const std::string& field, const std::string& message,
|
||||
int status) const {
|
||||
st_->denials.record(guard, message);
|
||||
if (!wants_html(req))
|
||||
return fw::JsonResponse("{\"error\":\"" + fw::json_escape(guard) +
|
||||
"\",\"field\":\"" + fw::json_escape(field) +
|
||||
"\",\"message\":\"" +
|
||||
fw::json_escape(message) + "\"}",
|
||||
status);
|
||||
fw::ValidationError err({{field, message}});
|
||||
v.values = fw::parse_form(req.body);
|
||||
v.error = &err;
|
||||
return show(v, status);
|
||||
}
|
||||
fw::Response ok(FormView v, const fw::Request& req, const std::string& notice,
|
||||
const std::string& json, int status = 200) const {
|
||||
if (!wants_html(req)) return fw::JsonResponse(json, status);
|
||||
v.done = true;
|
||||
v.notice = notice;
|
||||
return show(v, status);
|
||||
}
|
||||
|
||||
private:
|
||||
fw::Environment* env_;
|
||||
SecState* st_;
|
||||
};
|
||||
|
||||
std::map<std::string, std::string> input_of(const fw::Request& req) {
|
||||
if (req.headers.get("Content-Type").find("json") != std::string::npos)
|
||||
return fw::parse_json_object_flat(req.body);
|
||||
return fw::parse_form(req.body);
|
||||
}
|
||||
|
||||
std::string get(const std::map<std::string, std::string>& m, const std::string& k) {
|
||||
auto it = m.find(k);
|
||||
return it == m.end() ? "" : it->second;
|
||||
}
|
||||
|
||||
FormView make_view(const std::string& title, const std::string& action,
|
||||
const std::string& submit, std::vector<FormField> fields) {
|
||||
FormView v;
|
||||
v.title = title;
|
||||
v.action = action;
|
||||
v.submit = submit;
|
||||
v.fields = std::move(fields);
|
||||
return v;
|
||||
}
|
||||
|
||||
std::string json_list(const std::vector<std::string>& items) {
|
||||
std::string out = "[";
|
||||
for (std::size_t i = 0; i < items.size(); ++i)
|
||||
out += (i ? "," : "") + std::string("\"") + fw::json_escape(items[i]) + "\"";
|
||||
return out + "]";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_security_extra_demo(fw::Router& router, Services& services) {
|
||||
auto st = std::make_shared<SecState>(services.cookie_secret + "-csrf");
|
||||
fw::Environment* env = services.templates.get();
|
||||
FormPage page(env, st.get());
|
||||
auto auth = services.auth;
|
||||
auto sessions = services.sessions;
|
||||
std::string secret = services.cookie_secret;
|
||||
|
||||
// ---- CSRF --------------------------------------------------------------
|
||||
auto csrf_view = [](const std::string& token) {
|
||||
FormView v = make_view("CSRF protected form", "/security/csrf", "Save",
|
||||
{{"csrf_token", "CSRF token", "text",
|
||||
"issued by the server; edit it to see a 403"},
|
||||
{"note", "Note", "text", "any text, 1 to 80 chars"}});
|
||||
v.values["csrf_token"] = token;
|
||||
return v;
|
||||
};
|
||||
router.get("/security/csrf", "csrf-form", [st, page, csrf_view](fw::Request) -> fw::Response {
|
||||
return page.show(csrf_view(st->csrf.issue()));
|
||||
});
|
||||
router.post("/security/csrf", "csrf-post", [st, page, csrf_view](fw::Request req) -> fw::Response {
|
||||
auto in = input_of(req);
|
||||
FormView v = csrf_view("");
|
||||
if (!st->csrf.verify(get(in, "csrf_token")))
|
||||
return page.fail(v, req, "CsrfGuard", "csrf_token",
|
||||
"missing or invalid CSRF token, reload the form", 403);
|
||||
std::string note = get(in, "note");
|
||||
if (note.empty() || note.size() > 80)
|
||||
return page.fail(v, req, "Validation", "note", "must be 1 to 80 characters", 422);
|
||||
return page.ok(v, req, "Saved: " + note,
|
||||
"{\"ok\":true,\"note\":\"" + fw::json_escape(note) + "\"}");
|
||||
});
|
||||
|
||||
// ---- CORS --------------------------------------------------------------
|
||||
router.get("/security/cors", "cors-info", [st](fw::Request) -> fw::Response {
|
||||
return fw::JsonResponse(
|
||||
"{\"allowed_origins\":[\"https://app.example.com\",\"https://admin.example.com\"],"
|
||||
"\"usage\":\"OPTIONS /security/cors with Origin and Access-Control-Request-Method\"}");
|
||||
});
|
||||
router.options("/security/cors", "cors-preflight", [st](fw::Request req) -> fw::Response {
|
||||
fw::Response res(204, "", "text/plain");
|
||||
if (!st->cors.apply_preflight(req, res)) {
|
||||
st->denials.record("CorsPolicy", "origin not allowed: " + req.headers.get("Origin"));
|
||||
return fw::JsonResponse("{\"error\":\"origin not allowed\"}", 403);
|
||||
}
|
||||
return res;
|
||||
});
|
||||
|
||||
// ---- Rate limiting -----------------------------------------------------
|
||||
router.get("/security/rate", "rate-limited", [st](fw::Request req) -> fw::Response {
|
||||
std::string key = req.headers.get("X-Client-Id");
|
||||
if (key.empty() || key.size() > 64) key = "anon";
|
||||
int retry = 0, remaining = 0;
|
||||
if (!st->limiter.hit(key, retry, remaining)) {
|
||||
st->denials.record("RateLimiter", "limit hit for " + key);
|
||||
fw::Response res = fw::JsonResponse(
|
||||
"{\"error\":\"rate_limited\",\"retry_after\":" + std::to_string(retry) + "}", 429);
|
||||
res.headers.set("Retry-After", std::to_string(retry));
|
||||
return res;
|
||||
}
|
||||
fw::Response res = fw::JsonResponse(
|
||||
"{\"ok\":true,\"limit\":" + std::to_string(st->limiter.limit()) +
|
||||
",\"window_seconds\":" + std::to_string(st->limiter.window()) +
|
||||
",\"remaining\":" + std::to_string(remaining) + "}");
|
||||
res.headers.set("X-RateLimit-Remaining", std::to_string(remaining));
|
||||
return res;
|
||||
});
|
||||
|
||||
// ---- Security headers --------------------------------------------------
|
||||
router.get("/security/headers", "security-headers", [](fw::Request) -> fw::Response {
|
||||
std::string names = "[";
|
||||
bool first = true;
|
||||
for (const auto& [k, v] : fw::SecurityHeaders::defaults()) {
|
||||
names += std::string(first ? "" : ",") + "{\"name\":\"" + k +
|
||||
"\",\"value\":\"" + fw::json_escape(v) + "\"}";
|
||||
first = false;
|
||||
}
|
||||
fw::Response res = fw::JsonResponse("{\"applied\":" + names + "]}");
|
||||
fw::SecurityHeaders::apply(res);
|
||||
return res;
|
||||
});
|
||||
|
||||
// ---- CSP with nonce and report endpoint --------------------------------
|
||||
router.get("/csp/page", "csp-page", [](fw::Request) -> fw::Response {
|
||||
std::string nonce = fw::SecureRandom::token_hex(16);
|
||||
fw::CspBuilder csp;
|
||||
csp.script_nonce(nonce).report_uri("/csp/report");
|
||||
std::string body =
|
||||
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">"
|
||||
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"
|
||||
"<title>CSP nonce</title></head><body><h1>CSP nonce demo</h1>"
|
||||
"<p id=\"out\">Script blocked.</p><p>Nonce: <code>" + nonce +
|
||||
"</code></p><p><a href=\"/csp/report\">Violation reports</a></p>"
|
||||
"<script nonce=\"" + nonce +
|
||||
"\">document.getElementById('out').textContent='Nonce script ran.';</script>"
|
||||
"</body></html>";
|
||||
fw::Response res(200, body, kHtml);
|
||||
res.headers.set(csp.header_name(), csp.build());
|
||||
return res;
|
||||
});
|
||||
router.get("/csp/report", "csp-report-list", [st](fw::Request) -> fw::Response {
|
||||
std::string out = "{\"total\":" + std::to_string(st->csp_reports.total()) + ",\"reports\":[";
|
||||
bool first = true;
|
||||
for (const auto& r : st->csp_reports.list()) {
|
||||
out += std::string(first ? "" : ",") + "\"" + fw::json_escape(r) + "\"";
|
||||
first = false;
|
||||
}
|
||||
return fw::JsonResponse(out + "]}");
|
||||
});
|
||||
router.post("/csp/report", "csp-report", [st](fw::Request req) -> fw::Response {
|
||||
if (!st->csp_reports.add(req.body)) {
|
||||
st->denials.record("CspReport", "empty or oversized report");
|
||||
return fw::JsonResponse("{\"error\":\"report empty or over 4096 bytes\"}", 400);
|
||||
}
|
||||
return fw::Response(204, "", "text/plain");
|
||||
});
|
||||
|
||||
// ---- Crypto: hash and HMAC --------------------------------------------
|
||||
auto hash_view = []() {
|
||||
return make_view("SHA-256 and HMAC-SHA256", "/crypto/hash", "Hash",
|
||||
{{"text", "Text", "text", "up to 4096 bytes"},
|
||||
{"key", "HMAC key", "text", "optional, default demo-key"}});
|
||||
};
|
||||
router.get("/crypto/hash", "crypto-hash-form", [page, hash_view](fw::Request) -> fw::Response {
|
||||
return page.show(hash_view());
|
||||
});
|
||||
router.post("/crypto/hash", "crypto-hash", [page, hash_view](fw::Request req) -> fw::Response {
|
||||
auto in = input_of(req);
|
||||
std::string text = get(in, "text");
|
||||
std::string key = get(in, "key");
|
||||
if (key.empty()) key = "demo-key";
|
||||
if (text.empty() || text.size() > fw::secaps::kMaxHashInput)
|
||||
return page.fail(hash_view(), req, "Validation", "text",
|
||||
"must be 1 to 4096 bytes", 422);
|
||||
std::string sha = fw::Sha256::hex(text);
|
||||
std::string mac = fw::to_hex(fw::Hmac::sha256(key, text));
|
||||
return page.ok(hash_view(), req, "sha256=" + sha + " hmac=" + mac,
|
||||
"{\"sha256\":\"" + sha + "\",\"hmac_sha256\":\"" + mac + "\"}");
|
||||
});
|
||||
|
||||
// ---- Crypto: secure random --------------------------------------------
|
||||
router.get("/crypto/random", "crypto-random", [](fw::Request req) -> fw::Response {
|
||||
long n = 16;
|
||||
try { n = std::stol(req.query_or("bytes", "16")); } catch (...) { n = -1; }
|
||||
if (n < 1 || n > static_cast<long>(fw::secaps::kMaxRandomBytes))
|
||||
return fw::JsonResponse("{\"error\":\"bytes must be 1 to 64\"}", 400);
|
||||
return fw::JsonResponse("{\"bytes\":" + std::to_string(n) + ",\"token\":\"" +
|
||||
fw::SecureRandom::token_hex(static_cast<std::size_t>(n)) + "\"}");
|
||||
});
|
||||
|
||||
// ---- Crypto: password hashing -----------------------------------------
|
||||
auto pw_view = []() {
|
||||
return make_view("Password hashing (DEMO)", "/crypto/password", "Hash",
|
||||
{{"password", "Password", "password",
|
||||
"8 to 128 chars; salted PBKDF2 at demo rounds, not production"}});
|
||||
};
|
||||
router.get("/crypto/password", "crypto-password-form", [page, pw_view](fw::Request) -> fw::Response {
|
||||
return page.show(pw_view());
|
||||
});
|
||||
router.post("/crypto/password", "crypto-password", [page, pw_view](fw::Request req) -> fw::Response {
|
||||
std::string pw = get(input_of(req), "password");
|
||||
if (pw.size() < 8 || pw.size() > 128)
|
||||
return page.fail(pw_view(), req, "Validation", "password",
|
||||
"must be 8 to 128 characters", 422);
|
||||
std::string stored = fw::PasswordHasher::hash(pw);
|
||||
bool good = fw::PasswordHasher::verify(pw, stored);
|
||||
bool bad = fw::PasswordHasher::verify(pw + "x", stored);
|
||||
return page.ok(pw_view(), req,
|
||||
"Stored form: " + stored + " (verify ok: " + (good ? "yes" : "no") +
|
||||
", wrong password: " + (bad ? "accepted" : "rejected") + ")",
|
||||
"{\"stored\":\"" + stored + "\",\"verify\":" + (good ? "true" : "false") +
|
||||
",\"verify_wrong\":" + (bad ? "true" : "false") + "}");
|
||||
});
|
||||
|
||||
// ---- Roles and permissions --------------------------------------------
|
||||
router.get("/security/roles", "roles-info", [st](fw::Request) -> fw::Response {
|
||||
std::string out = "{\"tokens\":{\"viewer-token\":\"viewer\",\"editor-token\":\"editor\","
|
||||
"\"admin-token\":\"admin\"},\"roles\":{";
|
||||
bool first = true;
|
||||
for (const char* r : {"viewer", "editor", "admin"}) {
|
||||
out += std::string(first ? "" : ",") + "\"" + r + "\":" + json_list(st->perms.permissions(r));
|
||||
first = false;
|
||||
}
|
||||
return fw::JsonResponse(out + "},\"usage\":\"GET /security/admin with Authorization: Bearer <token>\"}");
|
||||
});
|
||||
router.get("/security/admin", "admin-area", [st](fw::Request req) -> fw::Response {
|
||||
std::string role;
|
||||
auto verdict = st->perms.check(req.headers.get("Authorization"), "admin:manage", role);
|
||||
if (verdict == fw::PermissionGuard::Verdict::Unauthenticated) {
|
||||
st->denials.record("Guard", "unauthenticated");
|
||||
fw::Response res = fw::JsonResponse("{\"error\":\"authentication required\"}", 401);
|
||||
res.headers.set("WWW-Authenticate", "Bearer");
|
||||
return res;
|
||||
}
|
||||
if (verdict == fw::PermissionGuard::Verdict::Forbidden) {
|
||||
st->denials.record("Guard", "role " + role + " lacks admin:manage");
|
||||
return fw::JsonResponse("{\"error\":\"forbidden\",\"role\":\"" + role + "\"}", 403);
|
||||
}
|
||||
return fw::JsonResponse("{\"ok\":true,\"role\":\"" + role + "\"}");
|
||||
});
|
||||
|
||||
// ---- Secrets provider -------------------------------------------------
|
||||
router.get("/security/secrets", "secrets", [st](fw::Request req) -> fw::Response {
|
||||
std::string name = req.query_or("name", "");
|
||||
if (!name.empty()) {
|
||||
std::string m;
|
||||
if (!st->secrets.masked(name, m))
|
||||
return fw::JsonResponse("{\"error\":\"unknown secret\"}", 404);
|
||||
return fw::JsonResponse("{\"name\":\"" + fw::json_escape(name) + "\",\"value\":\"" + m + "\"}");
|
||||
}
|
||||
return fw::JsonResponse("{\"names\":" + json_list(st->secrets.names()) +
|
||||
",\"note\":\"values are always masked\"}");
|
||||
});
|
||||
|
||||
// ---- Upload validation ------------------------------------------------
|
||||
auto up_view = []() {
|
||||
return make_view("Upload validation", "/security/upload", "Check",
|
||||
{{"filename", "File name", "text", "pdf, png or txt"},
|
||||
{"content_hex", "Content (hex bytes)", "text",
|
||||
"pdf starts 255044462d, png starts 89504e47, max 1024 bytes"}});
|
||||
};
|
||||
router.get("/security/upload", "upload-check-form", [page, up_view](fw::Request) -> fw::Response {
|
||||
return page.show(up_view());
|
||||
});
|
||||
router.post("/security/upload", "upload-check", [page, up_view](fw::Request req) -> fw::Response {
|
||||
auto in = input_of(req);
|
||||
std::string bytes;
|
||||
std::string hex = get(in, "content_hex");
|
||||
if (hex.size() > fw::secaps::kMaxUploadHex || !fw::from_hex(hex, bytes))
|
||||
return page.fail(up_view(), req, "UploadValidator", "content_hex",
|
||||
"must be an even number of hex digits, at most 4096", 422);
|
||||
std::string why = fw::UploadValidator::check(get(in, "filename"), bytes);
|
||||
if (!why.empty()) {
|
||||
bool big = why.find("too large") != std::string::npos;
|
||||
return page.fail(up_view(), req, "UploadValidator",
|
||||
why.find("file name") != std::string::npos ||
|
||||
why.find("extension") != std::string::npos
|
||||
? "filename"
|
||||
: "content_hex",
|
||||
why, big ? 413 : 422);
|
||||
}
|
||||
return page.ok(up_view(), req, "Accepted " + get(in, "filename") + " (" +
|
||||
std::to_string(bytes.size()) + " bytes)",
|
||||
"{\"ok\":true,\"size\":" + std::to_string(bytes.size()) + "}");
|
||||
});
|
||||
|
||||
// ---- SQL safety and path guard ----------------------------------------
|
||||
auto guard_view = []() {
|
||||
return make_view("SQL and path guard", "/security/guard", "Check",
|
||||
{{"kind", "Kind", "text", "sql or path"},
|
||||
{"value", "Value", "text", "try ' OR 1=1 -- or ../etc/passwd"}});
|
||||
};
|
||||
router.get("/security/guard", "guard-form", [page, guard_view](fw::Request) -> fw::Response {
|
||||
return page.show(guard_view());
|
||||
});
|
||||
router.post("/security/guard", "guard-check", [page, guard_view](fw::Request req) -> fw::Response {
|
||||
auto in = input_of(req);
|
||||
std::string kind = get(in, "kind"), value = get(in, "value");
|
||||
if (kind != "sql" && kind != "path")
|
||||
return page.fail(guard_view(), req, "Validation", "kind", "must be sql or path", 422);
|
||||
if (value.empty() || value.size() > fw::secaps::kMaxInputLen)
|
||||
return page.fail(guard_view(), req, "Validation", "value", "must be 1 to 512 characters", 422);
|
||||
std::string why = kind == "sql" ? fw::SqlSafety::check(value) : fw::PathGuard::check(value);
|
||||
if (!why.empty())
|
||||
return page.fail(guard_view(), req, kind == "sql" ? "SqlSafety" : "PathGuard", "value", why, 422);
|
||||
return page.ok(guard_view(), req, "Value is safe for " + kind,
|
||||
"{\"ok\":true,\"kind\":\"" + kind + "\"}");
|
||||
});
|
||||
|
||||
// ---- Denial sink ------------------------------------------------------
|
||||
router.get("/security/denials", "denials", [st](fw::Request) -> fw::Response {
|
||||
std::string out = "{\"total\":" + std::to_string(st->denials.total()) + ",\"recent\":[";
|
||||
bool first = true;
|
||||
for (const auto& d : st->denials.list()) {
|
||||
out += std::string(first ? "" : ",") + "{\"guard\":\"" + fw::json_escape(d.guard) +
|
||||
"\",\"reason\":\"" + fw::json_escape(d.reason) + "\"}";
|
||||
first = false;
|
||||
}
|
||||
return fw::JsonResponse(out + "]}");
|
||||
});
|
||||
|
||||
// ---- Login form with session cookie -----------------------------------
|
||||
auto login_view = []() {
|
||||
return make_view("Sign in", "/security/login", "Sign in",
|
||||
{{"username", "Username", "text", "demo: ada"},
|
||||
{"password", "Password", "password", "demo: correct-horse"}});
|
||||
};
|
||||
router.get("/security/login", "login-form", [page, login_view](fw::Request) -> fw::Response {
|
||||
return page.show(login_view());
|
||||
});
|
||||
router.post("/security/login", "login-post",
|
||||
[page, login_view, auth, sessions, secret](fw::Request req) -> fw::Response {
|
||||
auto in = input_of(req);
|
||||
std::string user = get(in, "username");
|
||||
if (user.empty() || user.size() > 64)
|
||||
return page.fail(login_view(), req, "Validation", "username", "is required (max 64)", 422);
|
||||
if (get(in, "password").empty())
|
||||
return page.fail(login_view(), req, "Validation", "password", "is required", 422);
|
||||
if (!auth->check(user, get(in, "password")))
|
||||
return page.fail(login_view(), req, "Authenticator", "password", "wrong username or password", 401);
|
||||
std::string id = sessions->create();
|
||||
sessions->put(id, "user", user);
|
||||
fw::Response res = page.ok(login_view(), req, "Signed in as " + user,
|
||||
"{\"user\":\"" + fw::json_escape(user) + "\"}");
|
||||
res.headers.set("Set-Cookie", fw::make_set_cookie("login_sid", fw::cookie_sign(id, secret),
|
||||
"/", true, false, "Lax", 3600));
|
||||
return res;
|
||||
});
|
||||
router.get("/security/whoami", "whoami", [sessions, secret](fw::Request req) -> fw::Response {
|
||||
std::string id;
|
||||
std::map<std::string, std::string> data;
|
||||
if (!fw::cookie_verify(req.cookie_or("login_sid", ""), secret, id) ||
|
||||
!sessions->get(id, data) || !data.count("user"))
|
||||
return fw::JsonResponse("{\"error\":\"not signed in\"}", 401);
|
||||
return fw::JsonResponse("{\"user\":\"" + fw::json_escape(data["user"]) + "\"}");
|
||||
});
|
||||
|
||||
services.add_feature("CSRF token form", "/security/csrf");
|
||||
services.add_feature("CORS preflight allowlist", "/security/cors");
|
||||
services.add_feature("Rate limiter (429 + Retry-After)", "/security/rate");
|
||||
services.add_feature("Security headers", "/security/headers");
|
||||
services.add_feature("CSP nonce page", "/csp/page");
|
||||
services.add_feature("CSP report endpoint", "/csp/report");
|
||||
services.add_feature("SHA-256 and HMAC", "/crypto/hash");
|
||||
services.add_feature("Secure random token", "/crypto/random");
|
||||
services.add_feature("Password hashing (demo)", "/crypto/password");
|
||||
services.add_feature("Roles and permissions", "/security/roles");
|
||||
services.add_feature("Secrets provider (masked)", "/security/secrets");
|
||||
services.add_feature("Upload validation", "/security/upload");
|
||||
services.add_feature("SQL and path guard", "/security/guard");
|
||||
services.add_feature("Denial sink", "/security/denials");
|
||||
services.add_feature("Login form with session cookie", "/security/login");
|
||||
}
|
||||
|
||||
} // namespace molo::example::app
|
||||
+9
-1
@@ -25,6 +25,10 @@ EXAMPLE_SRCS = \
|
||||
$(EXAMPLE_DIR)/fw/Tls.cpp \
|
||||
$(EXAMPLE_DIR)/fw/Kv.cpp \
|
||||
$(EXAMPLE_DIR)/fw/Stats.cpp \
|
||||
$(EXAMPLE_DIR)/fw/SecurityExtra.cpp \
|
||||
$(EXAMPLE_DIR)/fw/Platform.cpp \
|
||||
$(EXAMPLE_DIR)/fw/Enterprise.cpp \
|
||||
$(EXAMPLE_DIR)/fw/Resilience.cpp \
|
||||
$(EXAMPLE_DIR)/fw/Observ.cpp \
|
||||
$(EXAMPLE_DIR)/fw/Data.cpp \
|
||||
$(EXAMPLE_DIR)/fw/Jobs.cpp \
|
||||
@@ -43,7 +47,11 @@ EXAMPLE_SRCS = \
|
||||
$(EXAMPLE_DIR)/app/FormatsDemo.cpp \
|
||||
$(EXAMPLE_DIR)/app/RealtimeDemo.cpp \
|
||||
$(EXAMPLE_DIR)/app/OpsDemo.cpp \
|
||||
$(EXAMPLE_DIR)/app/StatsDemo.cpp
|
||||
$(EXAMPLE_DIR)/app/StatsDemo.cpp \
|
||||
$(EXAMPLE_DIR)/app/SecurityExtraDemo.cpp \
|
||||
$(EXAMPLE_DIR)/app/PlatformDemo.cpp \
|
||||
$(EXAMPLE_DIR)/app/EnterpriseDemo.cpp \
|
||||
$(EXAMPLE_DIR)/app/ResilienceDemo.cpp
|
||||
|
||||
# Tests are discovered: every tests/example/**/*_test.cpp is one route test.
|
||||
EXAMPLE_TEST_JOBS ?= 8
|
||||
|
||||
@@ -0,0 +1,544 @@
|
||||
#include "Enterprise.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <regex>
|
||||
#include <sstream>
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
namespace {
|
||||
|
||||
std::uint32_t rotr(std::uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }
|
||||
|
||||
std::vector<std::string> split(const std::string& s, char sep) {
|
||||
std::vector<std::string> out;
|
||||
std::string cur;
|
||||
for (char c : s) {
|
||||
if (c == sep) {
|
||||
out.push_back(cur);
|
||||
cur.clear();
|
||||
} else {
|
||||
cur += c;
|
||||
}
|
||||
}
|
||||
out.push_back(cur);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string trim(const std::string& s) {
|
||||
std::size_t a = s.find_first_not_of(" \t\r\n");
|
||||
if (a == std::string::npos) return "";
|
||||
return s.substr(a, s.find_last_not_of(" \t\r\n") - a + 1);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string sha256_hex(const std::string& data) {
|
||||
static const std::uint32_t k[64] = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
|
||||
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
||||
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
|
||||
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
|
||||
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
||||
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
|
||||
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
|
||||
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
||||
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
|
||||
std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
||||
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
|
||||
std::string msg = data;
|
||||
const std::uint64_t bits = static_cast<std::uint64_t>(data.size()) * 8;
|
||||
msg += static_cast<char>(0x80);
|
||||
while (msg.size() % 64 != 56) msg += '\0';
|
||||
for (int i = 7; i >= 0; --i) msg += static_cast<char>((bits >> (i * 8)) & 0xff);
|
||||
for (std::size_t off = 0; off < msg.size(); off += 64) {
|
||||
std::uint32_t w[64];
|
||||
for (int i = 0; i < 16; ++i)
|
||||
w[i] = (static_cast<std::uint32_t>(static_cast<unsigned char>(msg[off + i * 4])) << 24) |
|
||||
(static_cast<std::uint32_t>(static_cast<unsigned char>(msg[off + i * 4 + 1])) << 16) |
|
||||
(static_cast<std::uint32_t>(static_cast<unsigned char>(msg[off + i * 4 + 2])) << 8) |
|
||||
static_cast<std::uint32_t>(static_cast<unsigned char>(msg[off + i * 4 + 3]));
|
||||
for (int i = 16; i < 64; ++i) {
|
||||
std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
|
||||
std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5],
|
||||
g = h[6], hh = h[7];
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
std::uint32_t s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
||||
std::uint32_t ch = (e & f) ^ (~e & g);
|
||||
std::uint32_t t1 = hh + s1 + ch + k[i] + w[i];
|
||||
std::uint32_t s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
||||
std::uint32_t mj = (a & b) ^ (a & c) ^ (b & c);
|
||||
std::uint32_t t2 = s0 + mj;
|
||||
hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d;
|
||||
h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
|
||||
}
|
||||
static const char* hex = "0123456789abcdef";
|
||||
std::string out;
|
||||
for (std::uint32_t v : h)
|
||||
for (int i = 28; i >= 0; i -= 4) out += hex[(v >> i) & 0xf];
|
||||
return out;
|
||||
}
|
||||
|
||||
Response problem_response(int status, const std::string& title,
|
||||
const std::string& detail,
|
||||
const std::string& instance) {
|
||||
std::string body = "{\"type\":\"about:blank\",\"title\":\"" + json_escape(title) +
|
||||
"\",\"status\":" + std::to_string(status) +
|
||||
",\"detail\":\"" + json_escape(detail) + "\"";
|
||||
if (!instance.empty()) body += ",\"instance\":\"" + json_escape(instance) + "\"";
|
||||
body += "}";
|
||||
return Response(status, body, "application/problem+json");
|
||||
}
|
||||
|
||||
// ---- tenancy ---------------------------------------------------------------
|
||||
bool TenantResolver::valid_id(const std::string& id) {
|
||||
if (id.size() < 2 || id.size() > 32) return false;
|
||||
for (char c : id)
|
||||
if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-')) return false;
|
||||
return id.front() != '-' && id.back() != '-';
|
||||
}
|
||||
|
||||
TenantRef TenantResolver::resolve(const Request& req,
|
||||
const std::string& path_tenant) const {
|
||||
TenantRef ref;
|
||||
std::string host = req.headers.get("Host");
|
||||
if (req.headers.has("X-Tenant-ID")) {
|
||||
ref.id = req.headers.get("X-Tenant-ID");
|
||||
ref.source = "header";
|
||||
} else if (!path_tenant.empty()) {
|
||||
ref.id = path_tenant;
|
||||
ref.source = "path";
|
||||
} else if (std::count(host.begin(), host.end(), '.') >= 2) {
|
||||
ref.id = host.substr(0, host.find('.'));
|
||||
ref.source = "subdomain";
|
||||
} else {
|
||||
ref.id = kDefaultTenant;
|
||||
ref.source = "default";
|
||||
}
|
||||
if (!valid_id(ref.id)) ref.error = "tenant id must be 2-32 chars of a-z, 0-9, '-'";
|
||||
return ref;
|
||||
}
|
||||
|
||||
TenantCatalog::TenantCatalog() {
|
||||
tenants_["demo"] = {"demo", "Demo Inc", "free"};
|
||||
tenants_["acme"] = {"acme", "Acme Corp", "pro"};
|
||||
tenants_["globex"] = {"globex", "Globex", "free"};
|
||||
}
|
||||
|
||||
const Tenant* TenantCatalog::find(const std::string& id) const {
|
||||
auto it = tenants_.find(id);
|
||||
return it == tenants_.end() ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
std::string TenantCatalog::provision(const std::string& id, const std::string& name,
|
||||
const std::string& plan) {
|
||||
if (!TenantResolver::valid_id(id)) return "bad id";
|
||||
if (tenants_.count(id)) return "exists";
|
||||
if (tenants_.size() >= kMaxTenants) return "tenant cap reached";
|
||||
tenants_[id] = {id, name, plan};
|
||||
return "";
|
||||
}
|
||||
|
||||
std::vector<Tenant> TenantCatalog::list() const {
|
||||
std::vector<Tenant> out;
|
||||
for (const auto& [k, v] : tenants_) out.push_back(v);
|
||||
return out;
|
||||
}
|
||||
|
||||
bool TenantData::add(const std::string& tenant, const std::string& item) {
|
||||
auto& rows = rows_[tenant];
|
||||
if (rows.size() >= kMaxPerTenant) return false;
|
||||
rows.push_back(item);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::string> TenantData::list(const std::string& tenant) const {
|
||||
auto it = rows_.find(tenant);
|
||||
return it == rows_.end() ? std::vector<std::string>{} : it->second;
|
||||
}
|
||||
|
||||
std::size_t TenantQuota::limit_for(const std::string& plan) {
|
||||
return plan == "pro" ? 10 : 3;
|
||||
}
|
||||
|
||||
bool TenantQuota::consume(const std::string& tenant, const std::string& plan) {
|
||||
auto& u = used_[tenant];
|
||||
if (u >= limit_for(plan)) return false;
|
||||
++u;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::size_t TenantQuota::used(const std::string& tenant) const {
|
||||
auto it = used_.find(tenant);
|
||||
return it == used_.end() ? 0 : it->second;
|
||||
}
|
||||
|
||||
FeatureFlags::FeatureFlags() {
|
||||
defaults_ = {{"beta-ui", false}, {"export", true}, {"audit-log", true}};
|
||||
}
|
||||
|
||||
bool FeatureFlags::known(const std::string& flag) const {
|
||||
return defaults_.count(flag) > 0;
|
||||
}
|
||||
|
||||
bool FeatureFlags::enabled(const std::string& tenant, const std::string& flag) const {
|
||||
auto o = overrides_.find(tenant + "/" + flag);
|
||||
if (o != overrides_.end()) return o->second;
|
||||
auto d = defaults_.find(flag);
|
||||
return d != defaults_.end() && d->second;
|
||||
}
|
||||
|
||||
bool FeatureFlags::set(const std::string& tenant, const std::string& flag, bool on) {
|
||||
const std::string key = tenant + "/" + flag;
|
||||
if (!overrides_.count(key) && overrides_.size() >= kMaxOverrides) return false;
|
||||
overrides_[key] = on;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::map<std::string, bool> FeatureFlags::effective(const std::string& tenant) const {
|
||||
std::map<std::string, bool> out;
|
||||
for (const auto& [f, v] : defaults_) out[f] = enabled(tenant, f);
|
||||
return out;
|
||||
}
|
||||
|
||||
ConfigOverlay::ConfigOverlay() {
|
||||
base_ = {{"theme", "light"}, {"page_size", "20"}, {"locale", "en"}};
|
||||
}
|
||||
|
||||
bool ConfigOverlay::known(const std::string& key) const { return base_.count(key) > 0; }
|
||||
|
||||
bool ConfigOverlay::set(const std::string& tenant, const std::string& key,
|
||||
const std::string& value) {
|
||||
std::size_t total = 0;
|
||||
for (const auto& [t, m] : overlay_) total += m.size();
|
||||
if (total >= kMaxOverrides && !overlay_[tenant].count(key)) return false;
|
||||
overlay_[tenant][key] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::map<std::string, std::string> ConfigOverlay::effective(const std::string& tenant) const {
|
||||
auto out = base_;
|
||||
auto it = overlay_.find(tenant);
|
||||
if (it != overlay_.end())
|
||||
for (const auto& [k, v] : it->second) out[k] = v;
|
||||
return out;
|
||||
}
|
||||
|
||||
void TenantMetrics::inc(const std::string& tenant, const std::string& name) {
|
||||
++counters_[tenant][name];
|
||||
}
|
||||
|
||||
std::map<std::string, std::map<std::string, std::uint64_t>> TenantMetrics::all() const {
|
||||
return counters_;
|
||||
}
|
||||
|
||||
// ---- audit -----------------------------------------------------------------
|
||||
std::string AuditChain::hash_of(const AuditRecord& r) {
|
||||
return sha256_hex(std::to_string(r.index) + "|" + r.actor + "|" + r.action + "|" +
|
||||
r.subject + "|" + r.detail + "|" + r.prev);
|
||||
}
|
||||
|
||||
bool AuditChain::append(const std::string& actor, const std::string& action,
|
||||
const std::string& subject, const std::string& detail) {
|
||||
if (records_.size() >= kMaxRecords) return false;
|
||||
AuditRecord r;
|
||||
r.index = records_.size();
|
||||
r.actor = actor;
|
||||
r.action = action;
|
||||
r.subject = subject;
|
||||
r.detail = detail;
|
||||
r.prev = records_.empty() ? std::string(64, '0') : records_.back().hash;
|
||||
r.hash = hash_of(r);
|
||||
records_.push_back(r);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<std::size_t> AuditChain::verify() const {
|
||||
std::string prev(64, '0');
|
||||
for (const auto& r : records_) {
|
||||
if (r.prev != prev || hash_of(r) != r.hash) return r.index;
|
||||
prev = r.hash;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
bool AuditChain::tamper(std::size_t index) {
|
||||
if (index >= records_.size()) return false;
|
||||
records_[index].detail += " (edited)";
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string PiiMasker::mask_email(const std::string& v) {
|
||||
auto at = v.find('@');
|
||||
if (at == std::string::npos || at == 0) return std::string(v.size(), '*');
|
||||
return v.substr(0, 1) + std::string(at - 1, '*') + v.substr(at);
|
||||
}
|
||||
|
||||
std::string PiiMasker::mask_card(const std::string& v) {
|
||||
std::string digits;
|
||||
for (char c : v)
|
||||
if (c >= '0' && c <= '9') digits += c;
|
||||
if (digits.size() < 4) return std::string(digits.size(), '*');
|
||||
return std::string(digits.size() - 4, '*') + digits.substr(digits.size() - 4);
|
||||
}
|
||||
|
||||
std::string PiiMasker::redact(const std::string& text, std::size_t* hits) {
|
||||
static const std::vector<std::pair<std::regex, std::string>> patterns = {
|
||||
{std::regex(R"([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})"), "[EMAIL]"},
|
||||
{std::regex(R"(\b(?:\d[ -]?){13,16}\b)"), "[CARD]"},
|
||||
{std::regex(R"(\b\d{3}-\d{2}-\d{4}\b)"), "[SSN]"},
|
||||
{std::regex(R"(\b\d{1,3}(?:\.\d{1,3}){3}\b)"), "[IP]"}};
|
||||
std::string out = text.substr(0, 2000);
|
||||
std::size_t n = 0;
|
||||
for (const auto& [re, tag] : patterns) {
|
||||
n += static_cast<std::size_t>(std::distance(
|
||||
std::sregex_iterator(out.begin(), out.end(), re), std::sregex_iterator()));
|
||||
out = std::regex_replace(out, re, tag);
|
||||
}
|
||||
if (hits) *hits = n;
|
||||
return out;
|
||||
}
|
||||
|
||||
RetentionStore::RetentionStore() {
|
||||
entries_ = {{"r1", "session", 45, false}, {"r2", "session", 3, false},
|
||||
{"r3", "invoice", 400, false}, {"r4", "invoice", 3000, false},
|
||||
{"r5", "log", 120, false}};
|
||||
}
|
||||
|
||||
int RetentionStore::max_age(const std::string& klass) {
|
||||
if (klass == "session") return 30;
|
||||
if (klass == "log") return 90;
|
||||
return 2555; // invoice: 7 years
|
||||
}
|
||||
|
||||
bool RetentionStore::set_hold(const std::string& id, bool hold) {
|
||||
for (auto& e : entries_)
|
||||
if (e.id == id) {
|
||||
e.hold = hold;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<std::string> RetentionStore::expired() const {
|
||||
std::vector<std::string> out;
|
||||
for (const auto& e : entries_)
|
||||
if (!e.hold && e.age_days > max_age(e.klass)) out.push_back(e.id);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::size_t RetentionStore::purge() {
|
||||
auto ids = expired();
|
||||
entries_.erase(std::remove_if(entries_.begin(), entries_.end(),
|
||||
[&](const RetentionEntry& e) {
|
||||
return std::find(ids.begin(), ids.end(), e.id) != ids.end();
|
||||
}),
|
||||
entries_.end());
|
||||
return ids.size();
|
||||
}
|
||||
|
||||
SubjectStore::SubjectStore() {
|
||||
tables_["profiles"] = {{"ada@example.com", "name=Ada"}, {"bob@example.com", "name=Bob"}};
|
||||
tables_["orders"] = {{"ada@example.com", "order=1001"}, {"ada@example.com", "order=1002"},
|
||||
{"bob@example.com", "order=2001"}};
|
||||
tables_["sessions"] = {{"ada@example.com", "ip=[IP]"}};
|
||||
}
|
||||
|
||||
std::map<std::string, std::vector<std::string>> SubjectStore::export_for(
|
||||
const std::string& subject) const {
|
||||
std::map<std::string, std::vector<std::string>> out;
|
||||
for (const auto& [t, rows] : tables_)
|
||||
for (const auto& [s, d] : rows)
|
||||
if (s == subject) out[t].push_back(d);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::size_t SubjectStore::erase(const std::string& subject) {
|
||||
std::size_t n = 0;
|
||||
for (auto& [t, rows] : tables_) {
|
||||
auto before = rows.size();
|
||||
rows.erase(std::remove_if(rows.begin(), rows.end(),
|
||||
[&](const auto& r) { return r.first == subject; }),
|
||||
rows.end());
|
||||
n += before - rows.size();
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// ---- governance ------------------------------------------------------------
|
||||
std::string ApiKeyStore::issue(const std::string& owner, const std::string& tier,
|
||||
const std::set<std::string>& scopes,
|
||||
std::string* id_out) {
|
||||
if (keys_.size() >= kMaxKeys) return "";
|
||||
++counter_;
|
||||
std::string secret = sha256_hex("molo-key|" + owner + "|" + std::to_string(counter_));
|
||||
std::string key = "mk_" + secret.substr(0, 32);
|
||||
ApiKeyInfo info;
|
||||
info.id = "key" + std::to_string(counter_);
|
||||
info.owner = owner;
|
||||
info.tier = tier;
|
||||
info.scopes = scopes;
|
||||
info.hash = sha256_hex(key);
|
||||
keys_.push_back(info);
|
||||
if (id_out) *id_out = info.id;
|
||||
return key;
|
||||
}
|
||||
|
||||
bool ApiKeyStore::revoke(const std::string& id) {
|
||||
for (auto& k : keys_)
|
||||
if (k.id == id) {
|
||||
k.revoked = true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
KeyResult ApiKeyStore::authenticate(const std::string& key, const std::string& scope,
|
||||
const ApiKeyInfo** info) const {
|
||||
if (key.empty()) return KeyResult::Missing;
|
||||
const std::string h = sha256_hex(key);
|
||||
for (const auto& k : keys_) {
|
||||
if (k.hash != h) continue;
|
||||
if (info) *info = &k;
|
||||
if (k.revoked) return KeyResult::Revoked;
|
||||
if (!scope.empty() && !k.scopes.count(scope)) return KeyResult::Forbidden;
|
||||
return KeyResult::Ok;
|
||||
}
|
||||
return KeyResult::Unknown;
|
||||
}
|
||||
|
||||
TierPolicy TierTable::find(const std::string& tier) {
|
||||
if (tier == "pro") return {"pro", 10};
|
||||
return {"free", 3};
|
||||
}
|
||||
|
||||
bool QuotaLedger::charge(const std::string& key_id, const TierPolicy& policy) {
|
||||
auto& u = used_[key_id];
|
||||
if (u < policy.per_min * 100) ++u; // hard cap on the counter itself
|
||||
return u <= policy.per_min;
|
||||
}
|
||||
|
||||
std::size_t QuotaLedger::used(const std::string& key_id) const {
|
||||
auto it = used_.find(key_id);
|
||||
return it == used_.end() ? 0 : it->second;
|
||||
}
|
||||
|
||||
void QuotaLedger::headers(const std::string& key_id, const TierPolicy& policy,
|
||||
Headers& out) const {
|
||||
std::size_t u = used(key_id);
|
||||
std::size_t remaining = u >= policy.per_min ? 0 : policy.per_min - u;
|
||||
out.set("X-Tier", policy.name);
|
||||
out.set("X-RateLimit-Limit", std::to_string(policy.per_min));
|
||||
out.set("X-RateLimit-Remaining", std::to_string(remaining));
|
||||
out.set("X-RateLimit-Reset", "60");
|
||||
if (u > policy.per_min) out.set("Retry-After", "60");
|
||||
}
|
||||
|
||||
VersionTable::VersionTable() {
|
||||
versions_ = {{"v1", true, "Sat, 31 Dec 2033 23:59:59 GMT", "/v2"},
|
||||
{"v2", false, "", ""}};
|
||||
}
|
||||
|
||||
const ApiVersion* VersionTable::find(const std::string& name) const {
|
||||
for (const auto& v : versions_)
|
||||
if (v.name == name) return &v;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void VersionTable::annotate(const std::string& name, Headers& out) const {
|
||||
const ApiVersion* v = find(name);
|
||||
if (!v) return;
|
||||
out.set("X-API-Version", v->name);
|
||||
if (!v->deprecated) return;
|
||||
out.set("Deprecation", "true");
|
||||
if (!v->sunset.empty()) out.set("Sunset", v->sunset);
|
||||
if (!v->successor.empty())
|
||||
out.set("Link", "<" + v->successor + "/items>; rel=\"successor-version\"");
|
||||
}
|
||||
|
||||
std::vector<LintFinding> RouteLinter::lint(const std::vector<std::string>& paths) {
|
||||
static const std::vector<std::string> verbs = {"get", "create", "delete", "update",
|
||||
"fetch", "remove"};
|
||||
std::vector<LintFinding> out;
|
||||
std::size_t n = 0;
|
||||
for (const auto& p : paths) {
|
||||
if (++n > kMaxPaths) break;
|
||||
if (p.size() > 1 && p.back() == '/') out.push_back({p, "no-trailing-slash"});
|
||||
for (char c : p)
|
||||
if (c >= 'A' && c <= 'Z') {
|
||||
out.push_back({p, "lowercase-only"});
|
||||
break;
|
||||
}
|
||||
if (p.find('_') != std::string::npos) out.push_back({p, "kebab-case"});
|
||||
for (const auto& seg : split(p, '/'))
|
||||
if (std::find(verbs.begin(), verbs.end(), seg) != verbs.end()) {
|
||||
out.push_back({p, "no-verbs-in-path"});
|
||||
break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct Op {
|
||||
std::set<std::string> required, optional;
|
||||
};
|
||||
|
||||
std::map<std::string, Op> parse_snapshot(const std::string& s) {
|
||||
std::map<std::string, Op> ops;
|
||||
std::size_t lines = 0;
|
||||
for (const auto& raw : split(s, '\n')) {
|
||||
std::string line = trim(raw);
|
||||
if (line.empty()) continue;
|
||||
if (++lines > SpecDiffer::kMaxLines) break;
|
||||
std::istringstream in(line);
|
||||
std::string method, path, tok;
|
||||
in >> method >> path;
|
||||
Op op;
|
||||
while (in >> tok) {
|
||||
auto eq = tok.find('=');
|
||||
if (eq == std::string::npos) continue;
|
||||
auto names = split(tok.substr(eq + 1), ',');
|
||||
auto& dst = tok.substr(0, eq) == "required" ? op.required : op.optional;
|
||||
for (auto& n : names)
|
||||
if (!n.empty()) dst.insert(n);
|
||||
}
|
||||
ops[method + " " + path] = op;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<DiffFinding> SpecDiffer::diff(const std::string& before,
|
||||
const std::string& after) {
|
||||
auto a = parse_snapshot(before);
|
||||
auto b = parse_snapshot(after);
|
||||
std::vector<DiffFinding> out;
|
||||
for (const auto& [name, op] : a) {
|
||||
auto it = b.find(name);
|
||||
if (it == b.end()) {
|
||||
out.push_back({"breaking", name, "operation removed"});
|
||||
continue;
|
||||
}
|
||||
for (const auto& r : it->second.required)
|
||||
if (!op.required.count(r))
|
||||
out.push_back({"breaking", name, "new required parameter " + r});
|
||||
for (const auto& r : op.required)
|
||||
if (!it->second.required.count(r) && !it->second.optional.count(r))
|
||||
out.push_back({"breaking", name, "parameter removed " + r});
|
||||
}
|
||||
for (const auto& [name, op] : b)
|
||||
if (!a.count(name)) out.push_back({"compatible", name, "operation added"});
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::example::fw
|
||||
@@ -0,0 +1,269 @@
|
||||
#pragma once
|
||||
|
||||
// Enterprise framework skeleton for the living example: multi-tenancy, audit
|
||||
// and compliance, API governance. Every class is bounded by a hard cap.
|
||||
// Gaps versus the real modules are listed in the report of the owning plan:
|
||||
// src/tenancy/*, src/audit/*, src/governance/*.
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "Http.hpp"
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
// ---- shared helpers -------------------------------------------------------
|
||||
std::string sha256_hex(const std::string& data); // self-contained SHA-256
|
||||
|
||||
// RFC 7807 problem+json (mirrors src/governance/problem.h).
|
||||
Response problem_response(int status, const std::string& title,
|
||||
const std::string& detail,
|
||||
const std::string& instance = "");
|
||||
|
||||
// ---- multi-tenancy (src/tenancy) -----------------------------------------
|
||||
struct TenantRef {
|
||||
std::string id;
|
||||
std::string source; // header, path, subdomain, default
|
||||
std::string error; // non-empty when the id is malformed
|
||||
};
|
||||
|
||||
class TenantResolver {
|
||||
public:
|
||||
static constexpr const char* kDefaultTenant = "demo";
|
||||
static bool valid_id(const std::string& id);
|
||||
// Precedence: header X-Tenant-ID, then path param, then Host subdomain.
|
||||
TenantRef resolve(const Request& req, const std::string& path_tenant = "") const;
|
||||
};
|
||||
|
||||
struct Tenant {
|
||||
std::string id, name, plan; // plan: free or pro
|
||||
};
|
||||
|
||||
class TenantCatalog {
|
||||
public:
|
||||
static constexpr std::size_t kMaxTenants = 64;
|
||||
TenantCatalog();
|
||||
const Tenant* find(const std::string& id) const;
|
||||
// Returns empty on success, else the failure reason.
|
||||
std::string provision(const std::string& id, const std::string& name,
|
||||
const std::string& plan);
|
||||
std::vector<Tenant> list() const;
|
||||
|
||||
private:
|
||||
std::map<std::string, Tenant> tenants_;
|
||||
};
|
||||
|
||||
// Data isolation: every access is keyed by tenant id.
|
||||
class TenantData {
|
||||
public:
|
||||
static constexpr std::size_t kMaxPerTenant = 50;
|
||||
bool add(const std::string& tenant, const std::string& item);
|
||||
std::vector<std::string> list(const std::string& tenant) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::vector<std::string>> rows_;
|
||||
};
|
||||
|
||||
class TenantQuota {
|
||||
public:
|
||||
static std::size_t limit_for(const std::string& plan);
|
||||
bool consume(const std::string& tenant, const std::string& plan);
|
||||
std::size_t used(const std::string& tenant) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::size_t> used_;
|
||||
};
|
||||
|
||||
class FeatureFlags {
|
||||
public:
|
||||
static constexpr std::size_t kMaxOverrides = 128;
|
||||
FeatureFlags();
|
||||
bool enabled(const std::string& tenant, const std::string& flag) const;
|
||||
bool set(const std::string& tenant, const std::string& flag, bool on);
|
||||
bool known(const std::string& flag) const;
|
||||
std::map<std::string, bool> effective(const std::string& tenant) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, bool> defaults_;
|
||||
std::map<std::string, bool> overrides_; // "tenant/flag"
|
||||
};
|
||||
|
||||
class ConfigOverlay {
|
||||
public:
|
||||
static constexpr std::size_t kMaxOverrides = 128;
|
||||
ConfigOverlay();
|
||||
bool set(const std::string& tenant, const std::string& key,
|
||||
const std::string& value);
|
||||
std::map<std::string, std::string> effective(const std::string& tenant) const;
|
||||
bool known(const std::string& key) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::string> base_;
|
||||
std::map<std::string, std::map<std::string, std::string>> overlay_;
|
||||
};
|
||||
|
||||
class TenantMetrics {
|
||||
public:
|
||||
void inc(const std::string& tenant, const std::string& name);
|
||||
std::map<std::string, std::map<std::string, std::uint64_t>> all() const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::map<std::string, std::uint64_t>> counters_;
|
||||
};
|
||||
|
||||
// ---- audit and compliance (src/audit) ------------------------------------
|
||||
struct AuditRecord {
|
||||
std::size_t index = 0;
|
||||
std::string actor, action, subject, detail, prev, hash;
|
||||
};
|
||||
|
||||
class AuditChain {
|
||||
public:
|
||||
static constexpr std::size_t kMaxRecords = 500;
|
||||
// False when the cap is reached (append-only: never evicts).
|
||||
bool append(const std::string& actor, const std::string& action,
|
||||
const std::string& subject, const std::string& detail);
|
||||
// First index whose hash or link is wrong, or nullopt when intact.
|
||||
std::optional<std::size_t> verify() const;
|
||||
bool tamper(std::size_t index); // test hook: flips one detail
|
||||
const std::vector<AuditRecord>& records() const { return records_; }
|
||||
|
||||
private:
|
||||
static std::string hash_of(const AuditRecord& r);
|
||||
std::vector<AuditRecord> records_;
|
||||
};
|
||||
|
||||
class PiiMasker {
|
||||
public:
|
||||
static std::string mask_email(const std::string& v);
|
||||
static std::string mask_card(const std::string& v);
|
||||
// Redaction patterns over free text: email, card, ssn, ipv4.
|
||||
static std::string redact(const std::string& text, std::size_t* hits = nullptr);
|
||||
};
|
||||
|
||||
struct RetentionEntry {
|
||||
std::string id, klass;
|
||||
int age_days = 0;
|
||||
bool hold = false;
|
||||
};
|
||||
|
||||
class RetentionStore {
|
||||
public:
|
||||
RetentionStore();
|
||||
static int max_age(const std::string& klass); // policy per class
|
||||
bool set_hold(const std::string& id, bool hold);
|
||||
// Dry run reports; a real purge removes. Held entries are never touched.
|
||||
std::vector<std::string> expired() const;
|
||||
std::size_t purge();
|
||||
const std::vector<RetentionEntry>& entries() const { return entries_; }
|
||||
|
||||
private:
|
||||
std::vector<RetentionEntry> entries_;
|
||||
};
|
||||
|
||||
class SubjectStore {
|
||||
public:
|
||||
SubjectStore();
|
||||
// table -> list of rows for subject
|
||||
std::map<std::string, std::vector<std::string>> export_for(
|
||||
const std::string& subject) const;
|
||||
// Cascade erase across all tables, returns rows removed.
|
||||
std::size_t erase(const std::string& subject);
|
||||
|
||||
private:
|
||||
std::map<std::string, std::vector<std::pair<std::string, std::string>>> tables_;
|
||||
};
|
||||
|
||||
// ---- API governance (src/governance) -------------------------------------
|
||||
struct ApiKeyInfo {
|
||||
std::string id, owner, tier, hash;
|
||||
std::set<std::string> scopes;
|
||||
bool revoked = false;
|
||||
};
|
||||
|
||||
enum class KeyResult { Ok, Missing, Unknown, Revoked, Forbidden };
|
||||
|
||||
class ApiKeyStore {
|
||||
public:
|
||||
static constexpr std::size_t kMaxKeys = 64;
|
||||
// Returns the plaintext key once; only the hash is stored. Empty at cap.
|
||||
std::string issue(const std::string& owner, const std::string& tier,
|
||||
const std::set<std::string>& scopes, std::string* id_out);
|
||||
bool revoke(const std::string& id);
|
||||
KeyResult authenticate(const std::string& key, const std::string& scope,
|
||||
const ApiKeyInfo** info) const;
|
||||
std::size_t size() const { return keys_.size(); }
|
||||
|
||||
private:
|
||||
std::vector<ApiKeyInfo> keys_;
|
||||
std::uint64_t counter_ = 0;
|
||||
};
|
||||
|
||||
struct TierPolicy {
|
||||
std::string name;
|
||||
std::size_t per_min = 0;
|
||||
};
|
||||
|
||||
class TierTable {
|
||||
public:
|
||||
static TierPolicy find(const std::string& tier);
|
||||
};
|
||||
|
||||
class QuotaLedger {
|
||||
public:
|
||||
// True when the call is within the tier budget; always counts the call.
|
||||
bool charge(const std::string& key_id, const TierPolicy& policy);
|
||||
std::size_t used(const std::string& key_id) const;
|
||||
void headers(const std::string& key_id, const TierPolicy& policy,
|
||||
Headers& out) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::size_t> used_;
|
||||
};
|
||||
|
||||
struct ApiVersion {
|
||||
std::string name;
|
||||
bool deprecated = false;
|
||||
std::string sunset; // HTTP date
|
||||
std::string successor; // path prefix
|
||||
};
|
||||
|
||||
class VersionTable {
|
||||
public:
|
||||
VersionTable();
|
||||
const ApiVersion* find(const std::string& name) const;
|
||||
void annotate(const std::string& name, Headers& out) const;
|
||||
const std::vector<ApiVersion>& all() const { return versions_; }
|
||||
|
||||
private:
|
||||
std::vector<ApiVersion> versions_;
|
||||
};
|
||||
|
||||
struct LintFinding {
|
||||
std::string path, rule;
|
||||
};
|
||||
|
||||
class RouteLinter {
|
||||
public:
|
||||
static constexpr std::size_t kMaxPaths = 100;
|
||||
static std::vector<LintFinding> lint(const std::vector<std::string>& paths);
|
||||
};
|
||||
|
||||
struct DiffFinding {
|
||||
std::string kind, operation; // kind: breaking or compatible
|
||||
std::string detail;
|
||||
};
|
||||
|
||||
class SpecDiffer {
|
||||
public:
|
||||
static constexpr std::size_t kMaxLines = 200;
|
||||
// Snapshot line: "METHOD /path required=a,b optional=c"
|
||||
static std::vector<DiffFinding> diff(const std::string& before,
|
||||
const std::string& after);
|
||||
};
|
||||
|
||||
} // namespace molo::example::fw
|
||||
@@ -0,0 +1,695 @@
|
||||
#include "Platform.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
namespace {
|
||||
|
||||
std::string lower(std::string s) {
|
||||
for (char& c : s) c = (char)std::tolower((unsigned char)c);
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string trim(const std::string& s) {
|
||||
std::size_t a = s.find_first_not_of(" \t");
|
||||
if (a == std::string::npos) return "";
|
||||
return s.substr(a, s.find_last_not_of(" \t") - a + 1);
|
||||
}
|
||||
|
||||
std::vector<std::string> split(const std::string& s, char sep) {
|
||||
std::vector<std::string> out;
|
||||
std::size_t start = 0;
|
||||
while (true) {
|
||||
std::size_t at = s.find(sep, start);
|
||||
out.push_back(trim(s.substr(start, at == std::string::npos ? at : at - start)));
|
||||
if (at == std::string::npos) break;
|
||||
start = at + 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// "gzip;q=0.5" -> token "gzip", q 0.5. Missing q is 1.
|
||||
void token_q(const std::string& part, std::string& token, double& q) {
|
||||
std::size_t semi = part.find(';');
|
||||
token = lower(trim(part.substr(0, semi)));
|
||||
q = 1.0;
|
||||
if (semi == std::string::npos) return;
|
||||
std::string rest = lower(trim(part.substr(semi + 1)));
|
||||
if (rest.rfind("q=", 0) == 0) q = std::atof(rest.c_str() + 2);
|
||||
}
|
||||
|
||||
bool parse_size(const std::string& s, std::size_t& out) {
|
||||
if (s.empty() || s.size() > 15) return false;
|
||||
std::size_t v = 0;
|
||||
for (char c : s) {
|
||||
if (c < '0' || c > '9') return false;
|
||||
v = v * 10 + (std::size_t)(c - '0');
|
||||
}
|
||||
out = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string hex_pad(unsigned long long v, std::size_t digits) {
|
||||
char buf[40];
|
||||
std::snprintf(buf, sizeof(buf), "%0*llx", (int)digits, v);
|
||||
std::string s = buf;
|
||||
return s.substr(s.size() - digits);
|
||||
}
|
||||
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---- i18n -----------------------------------------------------------------
|
||||
|
||||
int PluralRule::forms(const std::string& locale) {
|
||||
if (locale == "ru") return 3;
|
||||
if (locale == "ja") return 1;
|
||||
return 2;
|
||||
}
|
||||
|
||||
int PluralRule::index(const std::string& locale, long n) {
|
||||
if (n < 0) n = -n;
|
||||
if (locale == "ja") return 0;
|
||||
if (locale == "fr") return n < 2 ? 0 : 1;
|
||||
if (locale == "ru") {
|
||||
if (n % 10 == 1 && n % 100 != 11) return 0;
|
||||
if (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14)) return 1;
|
||||
return 2;
|
||||
}
|
||||
return n == 1 ? 0 : 1;
|
||||
}
|
||||
|
||||
bool MessageCatalog::add(const std::string& locale, const std::string& msgid,
|
||||
std::vector<std::string> forms) {
|
||||
if (!data_.count(locale) && data_.size() >= platform_caps::kMaxLocales)
|
||||
return false;
|
||||
auto& msgs = data_[locale];
|
||||
if (!msgs.count(msgid) && msgs.size() >= platform_caps::kMaxMessages)
|
||||
return false;
|
||||
msgs[msgid] = std::move(forms);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string MessageCatalog::translate(const std::string& locale,
|
||||
const std::string& msgid, long n) const {
|
||||
for (const std::string& loc : {locale, default_}) {
|
||||
auto l = data_.find(loc);
|
||||
if (l == data_.end()) continue;
|
||||
auto m = l->second.find(msgid);
|
||||
if (m == l->second.end() || m->second.empty()) continue;
|
||||
std::size_t idx = (std::size_t)PluralRule::index(loc, n);
|
||||
const std::string& form = m->second[std::min(idx, m->second.size() - 1)];
|
||||
std::string out = form;
|
||||
std::size_t at = out.find("%d");
|
||||
if (at != std::string::npos) out.replace(at, 2, std::to_string(n));
|
||||
return out;
|
||||
}
|
||||
return msgid;
|
||||
}
|
||||
|
||||
std::vector<std::string> MessageCatalog::locales() const {
|
||||
std::vector<std::string> out;
|
||||
for (const auto& [k, v] : data_) out.push_back(k);
|
||||
return out;
|
||||
}
|
||||
|
||||
bool MessageCatalog::has_locale(const std::string& locale) const {
|
||||
return data_.count(locale) > 0;
|
||||
}
|
||||
|
||||
std::string MessageCatalog::to_po(const std::string& locale) const {
|
||||
auto l = data_.find(locale);
|
||||
std::string out = "msgid \"\"\nmsgstr \"\"\n\"Language: " + locale +
|
||||
"\\n\"\n\"Plural-Forms: nplurals=" +
|
||||
std::to_string(PluralRule::forms(locale)) + ";\\n\"\n";
|
||||
if (l == data_.end()) return out;
|
||||
for (const auto& [id, forms] : l->second) {
|
||||
out += "\nmsgid \"" + id + "\"\n";
|
||||
if (forms.size() == 1) {
|
||||
out += "msgstr \"" + forms[0] + "\"\n";
|
||||
} else {
|
||||
out += "msgid_plural \"" + id + "\"\n";
|
||||
for (std::size_t i = 0; i < forms.size(); ++i)
|
||||
out += "msgstr[" + std::to_string(i) + "] \"" + forms[i] + "\"\n";
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void MessageCatalog::set_default(std::string locale) {
|
||||
default_ = std::move(locale);
|
||||
}
|
||||
const std::string& MessageCatalog::default_locale() const { return default_; }
|
||||
|
||||
std::string negotiate_locale(const std::string& lang_param,
|
||||
const std::string& accept_language,
|
||||
const MessageCatalog& catalog) {
|
||||
std::string forced = lower(lang_param);
|
||||
if (catalog.has_locale(forced)) return forced;
|
||||
std::string best = catalog.default_locale();
|
||||
double best_q = 0;
|
||||
for (const std::string& part : split(accept_language, ',')) {
|
||||
if (part.empty()) continue;
|
||||
std::string tag;
|
||||
double q;
|
||||
token_q(part, tag, q);
|
||||
std::string primary = tag.substr(0, tag.find('-'));
|
||||
std::string pick = catalog.has_locale(tag) ? tag
|
||||
: catalog.has_locale(primary) ? primary
|
||||
: "";
|
||||
if (!pick.empty() && q > best_q) {
|
||||
best = pick;
|
||||
best_q = q;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// ---- compression ----------------------------------------------------------
|
||||
|
||||
std::uint32_t crc32(const std::string& data) {
|
||||
std::uint32_t crc = 0xFFFFFFFFu;
|
||||
for (unsigned char c : data) {
|
||||
crc ^= c;
|
||||
for (int k = 0; k < 8; ++k) crc = (crc >> 1) ^ (0xEDB88320u & (0u - (crc & 1u)));
|
||||
}
|
||||
return ~crc;
|
||||
}
|
||||
|
||||
namespace {
|
||||
void put_le32(std::string& out, std::uint32_t v) {
|
||||
for (int i = 0; i < 4; ++i) out.push_back((char)((v >> (8 * i)) & 0xFF));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string gzip_stored(const std::string& data) {
|
||||
std::string out("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff", 10);
|
||||
std::size_t pos = 0;
|
||||
do {
|
||||
std::size_t n = std::min<std::size_t>(65535, data.size() - pos);
|
||||
bool last = pos + n >= data.size();
|
||||
out.push_back(last ? 1 : 0);
|
||||
out.push_back((char)(n & 0xFF));
|
||||
out.push_back((char)(n >> 8));
|
||||
out.push_back((char)(~n & 0xFF));
|
||||
out.push_back((char)((~n >> 8) & 0xFF));
|
||||
out.append(data, pos, n);
|
||||
pos += n;
|
||||
} while (pos < data.size());
|
||||
put_le32(out, crc32(data));
|
||||
put_le32(out, (std::uint32_t)data.size());
|
||||
return out;
|
||||
}
|
||||
|
||||
bool accepts_encoding(const std::string& accept_encoding,
|
||||
const std::string& coding) {
|
||||
bool star = false;
|
||||
for (const std::string& part : split(accept_encoding, ',')) {
|
||||
std::string tag;
|
||||
double q;
|
||||
token_q(part, tag, q);
|
||||
if (tag == coding) return q > 0;
|
||||
if (tag == "*" && q > 0) star = true;
|
||||
}
|
||||
return star;
|
||||
}
|
||||
|
||||
// ---- conditional GET and ranges -------------------------------------------
|
||||
|
||||
std::string make_etag(const std::string& body) {
|
||||
std::uint64_t h = 1469598103934665603ull;
|
||||
for (unsigned char c : body) {
|
||||
h ^= c;
|
||||
h *= 1099511628211ull;
|
||||
}
|
||||
return "\"" + hex_pad(h, 16) + "-" + std::to_string(body.size()) + "\"";
|
||||
}
|
||||
|
||||
bool etag_matches(const std::string& header, const std::string& etag) {
|
||||
if (trim(header) == "*") return true;
|
||||
for (std::string tag : split(header, ',')) {
|
||||
if (tag.rfind("W/", 0) == 0) tag = tag.substr(2);
|
||||
if (!tag.empty() && tag == etag) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
ByteRange parse_range(const std::string& header, std::size_t size) {
|
||||
ByteRange r;
|
||||
if (header.rfind("bytes=", 0) != 0) return r;
|
||||
std::string spec = trim(header.substr(6));
|
||||
if (spec.find(',') != std::string::npos) return r;
|
||||
std::size_t dash = spec.find('-');
|
||||
if (dash == std::string::npos) return r;
|
||||
std::string a = spec.substr(0, dash), b = spec.substr(dash + 1);
|
||||
std::size_t first = 0, last = 0;
|
||||
if (a.empty()) {
|
||||
std::size_t n;
|
||||
if (!parse_size(b, n)) return r;
|
||||
r.kind = (n == 0 || size == 0) ? ByteRange::Kind::Unsatisfiable
|
||||
: ByteRange::Kind::Ok;
|
||||
if (r.kind == ByteRange::Kind::Ok) {
|
||||
r.first = n >= size ? 0 : size - n;
|
||||
r.last = size - 1;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
if (!parse_size(a, first)) return r;
|
||||
if (b.empty()) {
|
||||
last = size ? size - 1 : 0;
|
||||
} else if (!parse_size(b, last)) {
|
||||
return r;
|
||||
}
|
||||
if (first >= size || first > last) {
|
||||
r.kind = ByteRange::Kind::Unsatisfiable;
|
||||
return r;
|
||||
}
|
||||
r.kind = ByteRange::Kind::Ok;
|
||||
r.first = first;
|
||||
r.last = std::min(last, size - 1);
|
||||
return r;
|
||||
}
|
||||
|
||||
// ---- health probes --------------------------------------------------------
|
||||
|
||||
bool HealthRegistry::add_check(const std::string& name, bool up) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (!checks_.count(name) && checks_.size() >= platform_caps::kMaxChecks)
|
||||
return false;
|
||||
checks_[name] = up;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HealthRegistry::set_check(const std::string& name, bool up) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = checks_.find(name);
|
||||
if (it == checks_.end()) return false;
|
||||
it->second = up;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HealthRegistry::add_startup_task(const std::string& name, bool done) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (!tasks_.count(name) && tasks_.size() >= platform_caps::kMaxChecks)
|
||||
return false;
|
||||
tasks_[name] = done;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HealthRegistry::set_startup_task(const std::string& name, bool done) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = tasks_.find(name);
|
||||
if (it == tasks_.end()) return false;
|
||||
it->second = done;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HealthRegistry::startup_complete() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
for (const auto& [k, v] : tasks_)
|
||||
if (!v) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HealthRegistry::ready() const {
|
||||
if (!startup_complete()) return false;
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
for (const auto& [k, v] : checks_)
|
||||
if (!v) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace {
|
||||
std::string bool_map_json(const std::map<std::string, bool>& m,
|
||||
const char* up, const char* down) {
|
||||
std::string out = "{";
|
||||
bool first = true;
|
||||
for (const auto& [k, v] : m) {
|
||||
out += std::string(first ? "" : ",") + "\"" + json_escape(k) + "\":\"" +
|
||||
(v ? up : down) + "\"";
|
||||
first = false;
|
||||
}
|
||||
return out + "}";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string HealthRegistry::liveness_json() const {
|
||||
long up = (long)std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::steady_clock::now() - started_)
|
||||
.count();
|
||||
return "{\"status\":\"alive\",\"uptime_seconds\":" + std::to_string(up) + "}";
|
||||
}
|
||||
|
||||
std::string HealthRegistry::readiness_json() const {
|
||||
bool ok = ready();
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return std::string("{\"status\":\"") + (ok ? "ready" : "not_ready") +
|
||||
"\",\"checks\":" + bool_map_json(checks_, "up", "down") + "}";
|
||||
}
|
||||
|
||||
std::string HealthRegistry::startup_json() const {
|
||||
bool ok = startup_complete();
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return std::string("{\"status\":\"") + (ok ? "started" : "starting") +
|
||||
"\",\"tasks\":" + bool_map_json(tasks_, "done", "pending") + "}";
|
||||
}
|
||||
|
||||
// ---- Prometheus -----------------------------------------------------------
|
||||
|
||||
PrometheusExporter::PrometheusExporter(const Metrics* metrics,
|
||||
const Stats* stats)
|
||||
: metrics_(metrics), stats_(stats) {}
|
||||
|
||||
std::string PrometheusExporter::sanitize(const std::string& name) {
|
||||
std::string out;
|
||||
for (char c : name) {
|
||||
bool ok = std::isalnum((unsigned char)c) || c == '_' || c == ':';
|
||||
out.push_back(ok ? c : '_');
|
||||
}
|
||||
if (out.empty() || std::isdigit((unsigned char)out[0])) out.insert(0, "_");
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string PrometheusExporter::render() const {
|
||||
std::string out;
|
||||
auto sample = [&out](const std::string& name, const char* type,
|
||||
const std::string& help, const std::string& value) {
|
||||
out += "# HELP " + name + " " + help + "\n# TYPE " + name + " " + type +
|
||||
"\n" + name + " " + value + "\n";
|
||||
};
|
||||
sample("molo_http_requests_total", "counter", "Requests served.",
|
||||
std::to_string(stats_->total_requests()));
|
||||
sample("molo_http_connections_total", "counter", "Connections accepted.",
|
||||
std::to_string(stats_->total_connections()));
|
||||
sample("molo_http_connections_active", "gauge", "Open connections.",
|
||||
std::to_string(stats_->active_connections()));
|
||||
for (const auto& [k, v] : metrics_->snapshot()) {
|
||||
char buf[64];
|
||||
std::snprintf(buf, sizeof(buf), "%g", v);
|
||||
sample("molo_example_" + sanitize(k), "gauge",
|
||||
"Example metric " + k + ".", buf);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- structured logging ---------------------------------------------------
|
||||
|
||||
bool parse_level(const std::string& name, LogLevel& out) {
|
||||
std::string n = lower(name);
|
||||
if (n == "debug") out = LogLevel::Debug;
|
||||
else if (n == "info") out = LogLevel::Info;
|
||||
else if (n == "warn") out = LogLevel::Warn;
|
||||
else if (n == "error") out = LogLevel::Error;
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string level_name(LogLevel level) {
|
||||
switch (level) {
|
||||
case LogLevel::Debug: return "debug";
|
||||
case LogLevel::Info: return "info";
|
||||
case LogLevel::Warn: return "warn";
|
||||
case LogLevel::Error: return "error";
|
||||
}
|
||||
return "info";
|
||||
}
|
||||
|
||||
std::string LogRing::redact(const std::string& message) {
|
||||
static const char* keys[] = {"password", "passwd", "token", "secret",
|
||||
"authorization", "api_key", "apikey"};
|
||||
std::string out = message;
|
||||
std::string low = lower(out);
|
||||
for (const char* key : keys) {
|
||||
std::string k = key;
|
||||
std::size_t from = 0;
|
||||
while ((from = low.find(k, from)) != std::string::npos) {
|
||||
std::size_t p = from + k.size();
|
||||
from = p;
|
||||
if (p >= out.size() || (out[p] != '=' && out[p] != ':')) continue;
|
||||
++p;
|
||||
while (p < out.size() && out[p] == ' ') ++p;
|
||||
std::size_t e = p;
|
||||
while (e < out.size() && !std::isspace((unsigned char)out[e]) &&
|
||||
out[e] != ',' && out[e] != ';' && out[e] != '&')
|
||||
++e;
|
||||
out.replace(p, e - p, "***");
|
||||
low = lower(out);
|
||||
from = p;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void LogRing::log(LogLevel level, std::string message,
|
||||
std::string correlation_id) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (level < min_) {
|
||||
++filtered_;
|
||||
return;
|
||||
}
|
||||
LogRecord r;
|
||||
r.seq = next_seq_++;
|
||||
r.ts = (long)std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch())
|
||||
.count();
|
||||
r.level = level;
|
||||
if (message.size() > platform_caps::kLogMessage)
|
||||
message.resize(platform_caps::kLogMessage);
|
||||
r.message = redact(message);
|
||||
r.correlation_id = std::move(correlation_id);
|
||||
ring_.push_back(std::move(r));
|
||||
while (ring_.size() > platform_caps::kLogRing) ring_.pop_front();
|
||||
}
|
||||
|
||||
std::vector<LogRecord> LogRing::last(std::size_t n, LogLevel min) const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
std::vector<LogRecord> out;
|
||||
for (auto it = ring_.rbegin(); it != ring_.rend() && out.size() < n; ++it)
|
||||
if (it->level >= min) out.push_back(*it);
|
||||
return out;
|
||||
}
|
||||
|
||||
void LogRing::set_min_level(LogLevel level) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
min_ = level;
|
||||
}
|
||||
LogLevel LogRing::min_level() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return min_;
|
||||
}
|
||||
std::size_t LogRing::size() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return ring_.size();
|
||||
}
|
||||
unsigned long LogRing::dropped_below_min() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return filtered_;
|
||||
}
|
||||
|
||||
std::string LogRing::to_json(const LogRecord& r) {
|
||||
return "{\"seq\":" + std::to_string(r.seq) + ",\"ts\":" +
|
||||
std::to_string(r.ts) + ",\"level\":\"" + level_name(r.level) +
|
||||
"\",\"msg\":\"" + json_escape(r.message) + "\",\"correlation_id\":\"" +
|
||||
json_escape(r.correlation_id) + "\"}";
|
||||
}
|
||||
|
||||
// ---- trace context --------------------------------------------------------
|
||||
|
||||
std::string TraceContext::traceparent() const {
|
||||
return "00-" + trace_id + "-" + span_id + "-" + flags;
|
||||
}
|
||||
|
||||
std::string TraceContextFactory::next_hex(std::size_t digits) {
|
||||
unsigned long long v = ++counter_;
|
||||
v *= 0x9E3779B97F4A7C15ull;
|
||||
std::string out = hex_pad(v, 16);
|
||||
while (out.size() < digits) out += hex_pad(v * (out.size() + 7), 16);
|
||||
return out.substr(0, digits);
|
||||
}
|
||||
|
||||
TraceContext TraceContextFactory::from_header(const std::string& header) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
TraceContext ctx;
|
||||
ctx.had_parent = !header.empty();
|
||||
auto parts = split(header, '-');
|
||||
auto is_hex = [](const std::string& s) {
|
||||
return !s.empty() && std::all_of(s.begin(), s.end(), [](char c) {
|
||||
return std::isxdigit((unsigned char)c) && !std::isupper((unsigned char)c);
|
||||
});
|
||||
};
|
||||
bool ok = parts.size() == 4 && parts[0].size() == 2 && is_hex(parts[0]) &&
|
||||
parts[0] != "ff" && parts[1].size() == 32 && is_hex(parts[1]) &&
|
||||
parts[1] != std::string(32, '0') && parts[2].size() == 16 &&
|
||||
is_hex(parts[2]) && parts[2] != std::string(16, '0') &&
|
||||
parts[3].size() == 2 && is_hex(parts[3]);
|
||||
if (ok) {
|
||||
ctx.trace_id = parts[1];
|
||||
ctx.parent_span_id = parts[2];
|
||||
ctx.flags = parts[3];
|
||||
} else {
|
||||
ctx.parent_valid = !ctx.had_parent;
|
||||
ctx.trace_id = next_hex(32);
|
||||
}
|
||||
ctx.span_id = next_hex(16);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
// ---- DI registry ----------------------------------------------------------
|
||||
|
||||
std::string lifetime_name(Lifetime l) {
|
||||
switch (l) {
|
||||
case Lifetime::Singleton: return "singleton";
|
||||
case Lifetime::Scoped: return "scoped";
|
||||
case Lifetime::Transient: return "transient";
|
||||
}
|
||||
return "singleton";
|
||||
}
|
||||
|
||||
bool ServiceRegistry::add(const std::string& name, Lifetime lifetime,
|
||||
std::function<std::string()> factory) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (!slots_.count(name) && slots_.size() >= platform_caps::kMaxServices)
|
||||
return false;
|
||||
Slot s;
|
||||
s.lifetime = lifetime;
|
||||
s.factory = std::move(factory);
|
||||
slots_[name] = std::move(s);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ServiceRegistry::resolve(const std::string& name, const std::string& scope,
|
||||
std::string& out) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = slots_.find(name);
|
||||
if (it == slots_.end()) return false;
|
||||
Slot& s = it->second;
|
||||
++s.resolved;
|
||||
if (s.lifetime == Lifetime::Singleton) {
|
||||
if (!s.built) {
|
||||
s.instance = s.factory();
|
||||
s.built = true;
|
||||
++s.created;
|
||||
}
|
||||
out = s.instance;
|
||||
} else if (s.lifetime == Lifetime::Scoped) {
|
||||
auto sc = s.scoped.find(scope);
|
||||
if (sc == s.scoped.end()) {
|
||||
if (s.scoped.size() >= 16) s.scoped.clear();
|
||||
sc = s.scoped.emplace(scope, s.factory()).first;
|
||||
++s.created;
|
||||
}
|
||||
out = sc->second;
|
||||
} else {
|
||||
out = s.factory();
|
||||
++s.created;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<ServiceRegistry::Entry> ServiceRegistry::list() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
std::vector<Entry> out;
|
||||
for (const auto& [k, s] : slots_)
|
||||
out.push_back({k, s.lifetime, s.created, s.resolved});
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- flash messages -------------------------------------------------------
|
||||
|
||||
std::string FlashCodec::encode(const std::string& message) {
|
||||
std::string m = message.substr(0, platform_caps::kFlashBytes);
|
||||
std::string out;
|
||||
for (unsigned char c : m) out += hex_pad(c, 2);
|
||||
return out;
|
||||
}
|
||||
|
||||
bool FlashCodec::decode(const std::string& cookie, std::string& message) {
|
||||
if (cookie.empty() || cookie.size() % 2 || cookie.size() > platform_caps::kFlashBytes * 2)
|
||||
return false;
|
||||
std::string out;
|
||||
for (std::size_t i = 0; i < cookie.size(); i += 2) {
|
||||
if (!std::isxdigit((unsigned char)cookie[i]) ||
|
||||
!std::isxdigit((unsigned char)cookie[i + 1]))
|
||||
return false;
|
||||
out.push_back((char)std::stoi(cookie.substr(i, 2), nullptr, 16));
|
||||
}
|
||||
message = out;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- expose stats ---------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
constexpr std::size_t kBuckets =
|
||||
(std::size_t)(platform_caps::kExposeWindowSec / platform_caps::kExposeBucketSec);
|
||||
}
|
||||
|
||||
ExposeStats::ExposeStats(long (*now_sec)()) : clock_(now_sec) {}
|
||||
|
||||
void ExposeStats::set_clock(long (*now_sec)()) { clock_ = now_sec; }
|
||||
|
||||
long ExposeStats::now() const {
|
||||
if (clock_) return clock_();
|
||||
return (long)std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
bool ExposeStats::known_method(const std::string& m) {
|
||||
static const char* names[] = {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"};
|
||||
for (const char* n : names)
|
||||
if (m == n) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ExposeStats::record(const std::string& method, unsigned long up,
|
||||
unsigned long down, unsigned long micros) {
|
||||
if (!known_method(method)) return false;
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
ExposeRow& row = rows_[method];
|
||||
++row.count;
|
||||
row.bytes_up += up;
|
||||
row.bytes_down += down;
|
||||
row.micros += micros;
|
||||
auto& win = windows_[method];
|
||||
if (win.empty()) win.resize(kBuckets);
|
||||
long slot = now() / platform_caps::kExposeBucketSec;
|
||||
Bucket& b = win[(std::size_t)slot % kBuckets];
|
||||
if (b.slot != slot) b = Bucket{slot, 0, 0};
|
||||
b.up += up;
|
||||
b.down += down;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::map<std::string, ExposeRow> ExposeStats::snapshot() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
std::map<std::string, ExposeRow> out;
|
||||
ExposeRow total;
|
||||
long cur = now() / platform_caps::kExposeBucketSec;
|
||||
for (const auto& [m, row] : rows_) {
|
||||
ExposeRow r = row;
|
||||
unsigned long up = 0, down = 0;
|
||||
for (const Bucket& b : windows_.at(m))
|
||||
if (b.slot > cur - (long)kBuckets && b.slot <= cur) {
|
||||
up += b.up;
|
||||
down += b.down;
|
||||
}
|
||||
r.kb_s_up = up / 1024.0 / platform_caps::kExposeWindowSec;
|
||||
r.kb_s_down = down / 1024.0 / platform_caps::kExposeWindowSec;
|
||||
total.count += r.count;
|
||||
total.bytes_up += r.bytes_up;
|
||||
total.bytes_down += r.bytes_down;
|
||||
total.micros += r.micros;
|
||||
total.kb_s_up += r.kb_s_up;
|
||||
total.kb_s_down += r.kb_s_down;
|
||||
out[m] = r;
|
||||
}
|
||||
out["_total"] = total;
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::example::fw
|
||||
@@ -0,0 +1,272 @@
|
||||
#pragma once
|
||||
|
||||
// Platform framework skeleton for the living example (namespace molo::example::fw):
|
||||
// i18n, gzip negotiation, ETag and Range, health probes, Prometheus export,
|
||||
// structured log ring, W3C trace context, DI registry, flash cookies,
|
||||
// expose stats. Every store has a hard cap; past a cap input is rejected or
|
||||
// the oldest entry is dropped, never grown.
|
||||
// Gap: the real modules are src/cli/i18n, src/runtime/compress,
|
||||
// src/runtime/static/etag.*, src/cli/ops, src/observability, src/app/di,
|
||||
// src/app/views/flash.h and src/realtime/expose/stats.*.
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "App.hpp"
|
||||
#include "Http.hpp"
|
||||
#include "Observ.hpp"
|
||||
#include "Stats.hpp"
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
namespace platform_caps {
|
||||
inline constexpr std::size_t kMaxLocales = 8;
|
||||
inline constexpr std::size_t kMaxMessages = 64;
|
||||
inline constexpr long kMaxPluralN = 1000000;
|
||||
inline constexpr std::size_t kMaxCompressBody = 65536;
|
||||
inline constexpr std::size_t kCompressMin = 256;
|
||||
inline constexpr std::size_t kMaxDocBytes = 4096;
|
||||
inline constexpr std::size_t kMaxChecks = 32;
|
||||
inline constexpr std::size_t kLogRing = 200;
|
||||
inline constexpr std::size_t kLogMessage = 500;
|
||||
inline constexpr std::size_t kMaxServices = 64;
|
||||
inline constexpr std::size_t kFlashBytes = 200;
|
||||
inline constexpr std::size_t kExposeMethods = 16;
|
||||
inline constexpr long kExposeWindowSec = 60;
|
||||
inline constexpr long kExposeBucketSec = 10;
|
||||
} // namespace platform_caps
|
||||
|
||||
// ---- i18n -----------------------------------------------------------------
|
||||
|
||||
class PluralRule {
|
||||
public:
|
||||
// Form index for count n in locale (en/nl/de: 2 forms, fr: 2, ru: 3, ja: 1).
|
||||
static int index(const std::string& locale, long n);
|
||||
static int forms(const std::string& locale);
|
||||
};
|
||||
|
||||
class MessageCatalog {
|
||||
public:
|
||||
bool add(const std::string& locale, const std::string& msgid,
|
||||
std::vector<std::string> forms);
|
||||
// Plural-aware lookup; falls back to the default locale, then the msgid.
|
||||
std::string translate(const std::string& locale, const std::string& msgid,
|
||||
long n = 1) const;
|
||||
std::vector<std::string> locales() const;
|
||||
bool has_locale(const std::string& locale) const;
|
||||
// gettext .po style dump of one locale.
|
||||
std::string to_po(const std::string& locale) const;
|
||||
void set_default(std::string locale);
|
||||
const std::string& default_locale() const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::map<std::string, std::vector<std::string>>> data_;
|
||||
std::string default_ = "en";
|
||||
};
|
||||
|
||||
// ?lang beats Accept-Language (q-weighted) beats the default.
|
||||
std::string negotiate_locale(const std::string& lang_param,
|
||||
const std::string& accept_language,
|
||||
const MessageCatalog& catalog);
|
||||
|
||||
// ---- compression ----------------------------------------------------------
|
||||
|
||||
std::uint32_t crc32(const std::string& data);
|
||||
// Valid gzip member using stored deflate blocks (same approach as
|
||||
// src/cli/embed/gzip_stored.cpp). Gap: no real LZ77 (src/runtime/compress/gzip.cpp).
|
||||
std::string gzip_stored(const std::string& data);
|
||||
bool accepts_encoding(const std::string& accept_encoding,
|
||||
const std::string& coding);
|
||||
|
||||
// ---- conditional GET and ranges -------------------------------------------
|
||||
|
||||
std::string make_etag(const std::string& body);
|
||||
// True when If-None-Match (list, weak tags, or *) matches etag.
|
||||
bool etag_matches(const std::string& header, const std::string& etag);
|
||||
|
||||
struct ByteRange {
|
||||
enum class Kind { None, Ok, Unsatisfiable } kind = Kind::None;
|
||||
std::size_t first = 0;
|
||||
std::size_t last = 0; // inclusive
|
||||
};
|
||||
// Single range only: "a-b", "a-", "-n". Multi-range is ignored (Kind::None).
|
||||
ByteRange parse_range(const std::string& header, std::size_t size);
|
||||
|
||||
// ---- health probes --------------------------------------------------------
|
||||
|
||||
class HealthRegistry {
|
||||
public:
|
||||
bool add_check(const std::string& name, bool up);
|
||||
bool set_check(const std::string& name, bool up);
|
||||
bool add_startup_task(const std::string& name, bool done);
|
||||
bool set_startup_task(const std::string& name, bool done);
|
||||
bool startup_complete() const;
|
||||
bool ready() const;
|
||||
std::string liveness_json() const;
|
||||
std::string readiness_json() const;
|
||||
std::string startup_json() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::map<std::string, bool> checks_;
|
||||
std::map<std::string, bool> tasks_;
|
||||
std::chrono::steady_clock::time_point started_ =
|
||||
std::chrono::steady_clock::now();
|
||||
};
|
||||
|
||||
// ---- Prometheus -----------------------------------------------------------
|
||||
|
||||
class PrometheusExporter {
|
||||
public:
|
||||
PrometheusExporter(const Metrics* metrics, const Stats* stats);
|
||||
// text exposition format 0.0.4: HELP, TYPE, samples.
|
||||
std::string render() const;
|
||||
static std::string sanitize(const std::string& name);
|
||||
|
||||
private:
|
||||
const Metrics* metrics_;
|
||||
const Stats* stats_;
|
||||
};
|
||||
|
||||
// ---- structured logging ---------------------------------------------------
|
||||
|
||||
enum class LogLevel { Debug = 0, Info = 1, Warn = 2, Error = 3 };
|
||||
bool parse_level(const std::string& name, LogLevel& out);
|
||||
std::string level_name(LogLevel level);
|
||||
|
||||
struct LogRecord {
|
||||
unsigned long seq = 0;
|
||||
long ts = 0;
|
||||
LogLevel level = LogLevel::Info;
|
||||
std::string message;
|
||||
std::string correlation_id;
|
||||
};
|
||||
|
||||
class LogRing {
|
||||
public:
|
||||
// Redacts secret=value style fields, caps the message, drops the oldest.
|
||||
void log(LogLevel level, std::string message, std::string correlation_id);
|
||||
std::vector<LogRecord> last(std::size_t n, LogLevel min) const;
|
||||
void set_min_level(LogLevel level);
|
||||
LogLevel min_level() const;
|
||||
std::size_t size() const;
|
||||
unsigned long dropped_below_min() const;
|
||||
static std::string redact(const std::string& message);
|
||||
static std::string to_json(const LogRecord& record);
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::deque<LogRecord> ring_;
|
||||
LogLevel min_ = LogLevel::Debug;
|
||||
unsigned long next_seq_ = 1;
|
||||
unsigned long filtered_ = 0;
|
||||
};
|
||||
|
||||
// ---- trace context --------------------------------------------------------
|
||||
|
||||
struct TraceContext {
|
||||
bool had_parent = false;
|
||||
bool parent_valid = true;
|
||||
std::string trace_id;
|
||||
std::string parent_span_id;
|
||||
std::string span_id;
|
||||
std::string flags = "01";
|
||||
std::string traceparent() const;
|
||||
};
|
||||
|
||||
class TraceContextFactory {
|
||||
public:
|
||||
// Continues a valid W3C traceparent, else starts a new trace.
|
||||
TraceContext from_header(const std::string& traceparent);
|
||||
|
||||
private:
|
||||
std::string next_hex(std::size_t digits);
|
||||
std::mutex mu_;
|
||||
unsigned long long counter_ = 0x1000;
|
||||
};
|
||||
|
||||
// ---- DI registry ----------------------------------------------------------
|
||||
|
||||
enum class Lifetime { Singleton, Scoped, Transient };
|
||||
std::string lifetime_name(Lifetime lifetime);
|
||||
|
||||
class ServiceRegistry {
|
||||
public:
|
||||
bool add(const std::string& name, Lifetime lifetime,
|
||||
std::function<std::string()> factory);
|
||||
// Singleton built once, scoped once per scope key (max 16 kept), transient
|
||||
// on every call.
|
||||
bool resolve(const std::string& name, const std::string& scope,
|
||||
std::string& out);
|
||||
struct Entry {
|
||||
std::string name;
|
||||
Lifetime lifetime;
|
||||
unsigned long created;
|
||||
unsigned long resolved;
|
||||
};
|
||||
std::vector<Entry> list() const;
|
||||
|
||||
private:
|
||||
struct Slot {
|
||||
Lifetime lifetime;
|
||||
std::function<std::string()> factory;
|
||||
std::string instance;
|
||||
std::map<std::string, std::string> scoped;
|
||||
bool built = false;
|
||||
unsigned long created = 0;
|
||||
unsigned long resolved = 0;
|
||||
};
|
||||
mutable std::mutex mu_;
|
||||
std::map<std::string, Slot> slots_;
|
||||
};
|
||||
|
||||
// ---- flash messages -------------------------------------------------------
|
||||
|
||||
class FlashCodec {
|
||||
public:
|
||||
static std::string encode(const std::string& message);
|
||||
static bool decode(const std::string& cookie, std::string& message);
|
||||
};
|
||||
|
||||
// ---- expose stats ---------------------------------------------------------
|
||||
|
||||
struct ExposeRow {
|
||||
unsigned long count = 0;
|
||||
unsigned long bytes_up = 0;
|
||||
unsigned long bytes_down = 0;
|
||||
unsigned long micros = 0;
|
||||
double kb_s_up = 0;
|
||||
double kb_s_down = 0;
|
||||
double avg_ms() const { return count ? micros / 1000.0 / count : 0.0; }
|
||||
};
|
||||
|
||||
class ExposeStats {
|
||||
public:
|
||||
explicit ExposeStats(long (*now_sec)() = nullptr);
|
||||
bool record(const std::string& method, unsigned long up,
|
||||
unsigned long down, unsigned long micros);
|
||||
// Rows by method plus "_total"; windowed kB/s over the last 60 s.
|
||||
std::map<std::string, ExposeRow> snapshot() const;
|
||||
void set_clock(long (*now_sec)());
|
||||
static bool known_method(const std::string& method);
|
||||
|
||||
private:
|
||||
struct Bucket {
|
||||
long slot = -1;
|
||||
unsigned long up = 0;
|
||||
unsigned long down = 0;
|
||||
};
|
||||
long now() const;
|
||||
mutable std::mutex mu_;
|
||||
long (*clock_)() = nullptr;
|
||||
std::map<std::string, ExposeRow> rows_;
|
||||
std::map<std::string, std::vector<Bucket>> windows_;
|
||||
};
|
||||
|
||||
} // namespace molo::example::fw
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,408 @@
|
||||
#pragma once
|
||||
|
||||
// Resilience, delivery, supply chain, clients and data-depth skeletons for the
|
||||
// living example (namespace molo::example::fw). Every class is a Lab: a small
|
||||
// self-contained state machine with injectable time, a bounded log, and a
|
||||
// uniform rows() view that the demo pages and the debug snapshot render.
|
||||
// Gaps are listed per class next to the real module in src/.
|
||||
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
namespace labcaps {
|
||||
constexpr std::size_t kLogLines = 20; // bounded log per lab
|
||||
constexpr long kMaxAdvanceMs = 3600000; // one clock step, 1 hour
|
||||
constexpr int kMaxThreads = 16; // singleflight callers
|
||||
constexpr std::size_t kMaxEntries = 5; // ttl store capacity (LRU)
|
||||
constexpr std::size_t kMaxAdvisories = 8; // supplychain advisory db
|
||||
constexpr int kMaxAttempts = 5; // client retry ceiling
|
||||
constexpr int kMaxFaults = 5; // chaos blast radius (faults)
|
||||
constexpr int kMaxPercent = 50; // chaos blast radius (percent)
|
||||
} // namespace labcaps
|
||||
|
||||
using LabRows = std::vector<std::pair<std::string, std::string>>;
|
||||
|
||||
// Injectable time so every state machine is deterministic in tests.
|
||||
class ManualClock {
|
||||
public:
|
||||
long now() const { return now_; }
|
||||
void advance(long ms);
|
||||
|
||||
private:
|
||||
long now_ = 0;
|
||||
};
|
||||
|
||||
std::string fnv_hex(const std::string& data); // 64 bit FNV-1a, hex
|
||||
std::string base64_encode(const std::string& data);
|
||||
|
||||
class Lab {
|
||||
public:
|
||||
virtual ~Lab() = default;
|
||||
virtual std::string name() const = 0;
|
||||
virtual LabRows rows() const = 0;
|
||||
std::vector<std::string> log() const;
|
||||
std::string json() const; // {"name":..,"state":{..},"log":[..]}
|
||||
|
||||
protected:
|
||||
void note(std::string line); // caller holds mu_
|
||||
mutable std::recursive_mutex mu_;
|
||||
|
||||
private:
|
||||
std::deque<std::string> log_;
|
||||
};
|
||||
|
||||
// src/operability/resilience/breaker.h
|
||||
class CircuitBreaker : public Lab {
|
||||
public:
|
||||
enum class State { Closed, Open, HalfOpen };
|
||||
CircuitBreaker(std::shared_ptr<ManualClock> clock, int threshold = 3,
|
||||
long open_ms = 30000);
|
||||
// Records one call. Returns false when the breaker rejected it (open).
|
||||
bool call(bool success);
|
||||
void tick(long ms);
|
||||
State state() const;
|
||||
std::string name() const override { return "breaker"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
State effective() const;
|
||||
std::shared_ptr<ManualClock> clock_;
|
||||
int threshold_;
|
||||
long open_ms_;
|
||||
State state_ = State::Closed;
|
||||
int failures_ = 0;
|
||||
long opened_at_ = 0;
|
||||
int rejected_ = 0;
|
||||
};
|
||||
std::string breaker_state_name(CircuitBreaker::State s);
|
||||
|
||||
// src/operability/resilience/bulkhead.h
|
||||
class Bulkhead : public Lab {
|
||||
public:
|
||||
enum class Admission { Admitted, Queued, Rejected };
|
||||
Bulkhead(int max_active = 2, int max_queue = 1);
|
||||
Admission acquire();
|
||||
bool release(); // false when nothing to release
|
||||
std::string name() const override { return "bulkhead"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
int max_active_, max_queue_, active_ = 0, queued_ = 0, rejected_ = 0;
|
||||
};
|
||||
|
||||
// src/operability/resilience/shedder.h
|
||||
class Shedder : public Lab {
|
||||
public:
|
||||
explicit Shedder(int limit = 3) : limit_(limit) {}
|
||||
// low priority is shed at 2/3 of the limit, high only at the limit.
|
||||
bool enter(bool high);
|
||||
bool leave();
|
||||
std::string name() const override { return "shedder"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
int limit_, inflight_ = 0, shed_low_ = 0, shed_high_ = 0;
|
||||
};
|
||||
|
||||
// src/operability/resilience/deadline.h
|
||||
class DeadlineLab : public Lab {
|
||||
public:
|
||||
static constexpr long kHopCostMs = 30;
|
||||
// Walks `hops` downstream calls against one propagated budget.
|
||||
// Returns the hop that expired (1 based) or 0 when all finished.
|
||||
int run(long budget_ms, int hops);
|
||||
std::string name() const override { return "deadline"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
long budget_ms_ = 0, remaining_ms_ = 0;
|
||||
int hops_ = 0, expired_hop_ = 0;
|
||||
bool ran_ = false;
|
||||
};
|
||||
|
||||
// src/operability/resilience/slo.h
|
||||
class SloBudget : public Lab {
|
||||
public:
|
||||
static constexpr std::size_t kWindow = 100; // ring of the last 100 events
|
||||
SloBudget(int target_permille = 950) : target_(target_permille) {}
|
||||
void record(bool good);
|
||||
void reset();
|
||||
long budget_remaining() const; // allowed bad events minus actual bad
|
||||
std::string name() const override { return "slo"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
int target_;
|
||||
std::deque<bool> window_;
|
||||
};
|
||||
|
||||
// src/operability/chaos/experiment.h, injector.h
|
||||
class ChaosLab : public Lab {
|
||||
public:
|
||||
static constexpr int kCalls = 10; // simulated calls per experiment
|
||||
struct Result {
|
||||
int percent = 0, max_faults = 0, planned = 0, injected = 0;
|
||||
bool armed = false;
|
||||
};
|
||||
// Deterministic: an accumulator injects a fault every 100/percent calls.
|
||||
// Dry run (armed=false) plans faults but never injects them.
|
||||
Result run(int percent, int max_faults, bool armed);
|
||||
std::string name() const override { return "chaos"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
Result last_;
|
||||
int runs_ = 0, total_injected_ = 0;
|
||||
};
|
||||
|
||||
// src/operability/deploy/rolling.h, blue_green.h, lifecycle.h
|
||||
class DeployLab : public Lab {
|
||||
public:
|
||||
enum class Phase { Idle, InProgress, Done, RolledBack };
|
||||
DeployLab();
|
||||
bool start(const std::string& strategy, const std::string& version);
|
||||
bool step();
|
||||
bool rollback();
|
||||
Phase phase() const;
|
||||
std::string name() const override { return "deploy"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
std::vector<std::string> fleet_, previous_;
|
||||
std::string strategy_ = "none", target_;
|
||||
int green_stage_ = 0; // blue-green: 0 prepare, 1 switched
|
||||
Phase phase_ = Phase::Idle;
|
||||
};
|
||||
std::string deploy_phase_name(DeployLab::Phase p);
|
||||
|
||||
// src/operability/coord/lease.h, election.h, dist_lock.h, fence.h
|
||||
class CoordLab : public Lab {
|
||||
public:
|
||||
struct Grant {
|
||||
bool ok = false;
|
||||
long token = 0;
|
||||
std::string holder;
|
||||
};
|
||||
explicit CoordLab(std::shared_ptr<ManualClock> clock, long ttl_ms = 10000);
|
||||
Grant acquire(const std::string& key, const std::string& owner);
|
||||
bool release(const std::string& key, const std::string& owner);
|
||||
// Fenced write: accepted only when token >= the highest token seen.
|
||||
bool write(const std::string& key, long token);
|
||||
void tick(long ms);
|
||||
static bool known_key(const std::string& key);
|
||||
std::string name() const override { return "coord"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
struct Slot {
|
||||
std::string holder;
|
||||
long expires = 0, token = 0, fence = 0;
|
||||
};
|
||||
std::shared_ptr<ManualClock> clock_;
|
||||
long ttl_ms_;
|
||||
std::map<std::string, Slot> slots_;
|
||||
};
|
||||
|
||||
// src/operability/debug/endpoint.h, snapshot.h
|
||||
class DebugRegistry {
|
||||
public:
|
||||
void add(std::shared_ptr<Lab> lab);
|
||||
std::string snapshot() const; // {"labs":{name:{..}}}
|
||||
std::size_t size() const { return labs_.size(); }
|
||||
|
||||
private:
|
||||
std::vector<std::shared_ptr<Lab>> labs_;
|
||||
};
|
||||
|
||||
// src/supplychain/sbom, policy, attest
|
||||
class SupplyChainLab : public Lab {
|
||||
public:
|
||||
struct Component {
|
||||
std::string name, version, license;
|
||||
};
|
||||
SupplyChainLab();
|
||||
bool add_advisory(const std::string& component, const std::string& version);
|
||||
void tamper();
|
||||
void reset();
|
||||
// True when `digest` equals the attested and the current SBOM digest.
|
||||
bool verify(const std::string& digest);
|
||||
std::string digest() const;
|
||||
std::string attested() const { return attested_; }
|
||||
bool gate() const;
|
||||
std::string cyclonedx() const;
|
||||
std::string name() const override { return "supplychain"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
bool pins_ok() const;
|
||||
bool advisories_ok() const;
|
||||
std::vector<Component> components_;
|
||||
std::map<std::string, std::string> pins_;
|
||||
std::vector<std::pair<std::string, std::string>> advisories_;
|
||||
std::string attested_;
|
||||
int verified_ = 0; // 0 none, 1 ok, -1 failed
|
||||
};
|
||||
|
||||
// src/clients/retry.h
|
||||
class ClientRetryLab : public Lab {
|
||||
public:
|
||||
struct Outcome {
|
||||
int attempts = 0, status = 0;
|
||||
long waited_ms = 0;
|
||||
bool gave_up = false;
|
||||
};
|
||||
// The in-process transport fails the first `failures` calls with `status`.
|
||||
// 5xx is retried with capped exponential backoff; 4xx never is.
|
||||
Outcome run(int failures, int max_attempts, int status);
|
||||
std::string name() const override { return "client-retry"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
static constexpr long kBaseMs = 100, kCapMs = 800;
|
||||
Outcome last_;
|
||||
int runs_ = 0;
|
||||
};
|
||||
|
||||
// src/clients/cookies.h, pool.h, proxy.h, auth.h
|
||||
class ClientSessionLab : public Lab {
|
||||
public:
|
||||
ClientSessionLab();
|
||||
static bool valid_proxy(const std::string& proxy);
|
||||
// One request through the in-process transport; returns the request headers.
|
||||
std::map<std::string, std::string> request(const std::string& auth,
|
||||
const std::string& proxy);
|
||||
std::string name() const override { return "client-session"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::string> jar_;
|
||||
int created_ = 0, reused_ = 0, idle_ = 0, requests_ = 0;
|
||||
std::string proxy_ = "direct", auth_ = "none";
|
||||
};
|
||||
|
||||
// src/data/orm/migration.hpp, migrator.hpp, healer.hpp
|
||||
class MigrationLab : public Lab {
|
||||
public:
|
||||
struct Step {
|
||||
std::string id, sql, table;
|
||||
};
|
||||
MigrationLab();
|
||||
// check: what apply would do, nothing changes.
|
||||
std::vector<std::string> check() const;
|
||||
int apply(int limit);
|
||||
void drop_table(const std::string& table); // simulated drift
|
||||
int heal(); // re-apply drifted creates
|
||||
std::vector<std::string> drift() const;
|
||||
std::string name() const override { return "migrations"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
std::vector<Step> steps_;
|
||||
std::vector<std::string> applied_;
|
||||
std::map<std::string, std::string> tables_; // table -> columns
|
||||
};
|
||||
|
||||
// src/data/transaction.hpp
|
||||
class TxLab : public Lab {
|
||||
public:
|
||||
TxLab();
|
||||
// Returns "committed", or the rollback reason.
|
||||
std::string transfer(const std::string& from, const std::string& to,
|
||||
long amount, bool fail_after_debit);
|
||||
long balance(const std::string& who) const;
|
||||
std::string name() const override { return "transaction"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
std::map<std::string, long> accounts_;
|
||||
int commits_ = 0, rollbacks_ = 0;
|
||||
};
|
||||
|
||||
// src/data/orm/query.hpp, relations.hpp
|
||||
class QueryLab : public Lab {
|
||||
public:
|
||||
struct Result {
|
||||
std::string sql;
|
||||
std::vector<std::map<std::string, std::string>> rows;
|
||||
};
|
||||
QueryLab();
|
||||
// Builds "SELECT ... FROM posts [WHERE user_id = ?] ORDER BY .. LIMIT n"
|
||||
// and executes it against the in-memory users/posts tables (has-many).
|
||||
Result run(long user_id, const std::string& order, int limit);
|
||||
std::string name() const override { return "query"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
std::vector<std::map<std::string, std::string>> users_, posts_;
|
||||
Result last_;
|
||||
};
|
||||
|
||||
// src/data/cache/singleflight.hpp
|
||||
class SingleFlight {
|
||||
public:
|
||||
// Concurrent callers of one key share a single loader execution.
|
||||
std::string run(const std::string& key,
|
||||
const std::function<std::string()>& loader);
|
||||
int waiters(const std::string& key) const;
|
||||
|
||||
private:
|
||||
struct Call {
|
||||
bool done = false;
|
||||
int waiters = 0;
|
||||
std::string value;
|
||||
};
|
||||
mutable std::mutex mu_;
|
||||
std::condition_variable_any cv_;
|
||||
std::map<std::string, std::shared_ptr<Call>> calls_;
|
||||
};
|
||||
|
||||
class SingleFlightLab : public Lab {
|
||||
public:
|
||||
SingleFlightLab();
|
||||
// Starts `callers` threads on one key; returns loader executions.
|
||||
int run(int callers);
|
||||
std::string name() const override { return "singleflight"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
std::unique_ptr<SingleFlight> flight_;
|
||||
int callers_ = 0, loads_ = 0, runs_ = 0;
|
||||
};
|
||||
|
||||
// src/data/kv/memory.hpp, src/data/cache/policy.hpp, src/data/pubsub/broker.hpp
|
||||
class TtlLab : public Lab {
|
||||
public:
|
||||
explicit TtlLab(std::shared_ptr<ManualClock> clock);
|
||||
void set(const std::string& key, const std::string& value, long ttl_s);
|
||||
// Returns true and fills value on a live hit.
|
||||
bool get(const std::string& key, std::string& value);
|
||||
void tick(long ms);
|
||||
std::size_t size() const;
|
||||
std::vector<std::string> events() const; // pubsub topic "kv.events"
|
||||
std::string name() const override { return "ttl"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
std::string value;
|
||||
long expires = 0, touched = 0;
|
||||
};
|
||||
void sweep();
|
||||
void publish(const std::string& event);
|
||||
std::shared_ptr<ManualClock> clock_;
|
||||
std::map<std::string, Entry> entries_;
|
||||
std::deque<std::string> events_;
|
||||
long seq_ = 0;
|
||||
int hits_ = 0, misses_ = 0;
|
||||
};
|
||||
|
||||
} // namespace molo::example::fw
|
||||
@@ -0,0 +1,390 @@
|
||||
#include "SecurityExtra.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
namespace {
|
||||
const char* kHex = "0123456789abcdef";
|
||||
inline std::uint32_t rotr(std::uint32_t x, int n) {
|
||||
return (x >> n) | (x << (32 - n));
|
||||
}
|
||||
const std::uint32_t kK[64] = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
|
||||
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
||||
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
|
||||
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
|
||||
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
||||
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
|
||||
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
|
||||
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
||||
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
|
||||
} // namespace
|
||||
|
||||
std::string to_hex(const std::string& raw) {
|
||||
std::string out;
|
||||
out.reserve(raw.size() * 2);
|
||||
for (unsigned char c : raw) {
|
||||
out += kHex[c >> 4];
|
||||
out += kHex[c & 15];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool from_hex(const std::string& hex, std::string& raw) {
|
||||
raw.clear();
|
||||
if (hex.size() % 2 != 0) return false;
|
||||
auto val = [](char c) -> int {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
};
|
||||
for (std::size_t i = 0; i < hex.size(); i += 2) {
|
||||
int a = val(hex[i]), b = val(hex[i + 1]);
|
||||
if (a < 0 || b < 0) return false;
|
||||
raw += static_cast<char>(a * 16 + b);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool constant_time_equal(const std::string& a, const std::string& b) {
|
||||
unsigned char diff = a.size() == b.size() ? 0 : 1;
|
||||
std::size_t n = std::min(a.size(), b.size());
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
diff |= static_cast<unsigned char>(a[i] ^ b[i]);
|
||||
return diff == 0;
|
||||
}
|
||||
|
||||
std::string Sha256::digest(const std::string& data) {
|
||||
std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
||||
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
|
||||
std::string msg = data;
|
||||
std::uint64_t bits = static_cast<std::uint64_t>(data.size()) * 8;
|
||||
msg += static_cast<char>(0x80);
|
||||
while (msg.size() % 64 != 56) msg += '\0';
|
||||
for (int i = 7; i >= 0; --i) msg += static_cast<char>((bits >> (i * 8)) & 0xff);
|
||||
for (std::size_t off = 0; off < msg.size(); off += 64) {
|
||||
std::uint32_t w[64];
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
const unsigned char* p =
|
||||
reinterpret_cast<const unsigned char*>(msg.data()) + off + i * 4;
|
||||
w[i] = (std::uint32_t(p[0]) << 24) | (std::uint32_t(p[1]) << 16) |
|
||||
(std::uint32_t(p[2]) << 8) | p[3];
|
||||
}
|
||||
for (int i = 16; i < 64; ++i) {
|
||||
std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
|
||||
std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5],
|
||||
g = h[6], hh = h[7];
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
std::uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
||||
std::uint32_t ch = (e & f) ^ (~e & g);
|
||||
std::uint32_t t1 = hh + S1 + ch + kK[i] + w[i];
|
||||
std::uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
||||
std::uint32_t mj = (a & b) ^ (a & c) ^ (b & c);
|
||||
std::uint32_t t2 = S0 + mj;
|
||||
hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d;
|
||||
h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
|
||||
}
|
||||
std::string out;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
for (int s = 24; s >= 0; s -= 8) out += static_cast<char>((h[i] >> s) & 0xff);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string Sha256::hex(const std::string& data) { return to_hex(digest(data)); }
|
||||
|
||||
std::string Hmac::sha256(const std::string& key, const std::string& data) {
|
||||
std::string k = key.size() > 64 ? Sha256::digest(key) : key;
|
||||
k.resize(64, '\0');
|
||||
std::string ipad(64, '\0'), opad(64, '\0');
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
ipad[i] = static_cast<char>(k[i] ^ 0x36);
|
||||
opad[i] = static_cast<char>(k[i] ^ 0x5c);
|
||||
}
|
||||
return Sha256::digest(opad + Sha256::digest(ipad + data));
|
||||
}
|
||||
|
||||
std::string SecureRandom::bytes(std::size_t n) {
|
||||
n = std::min(n, secaps::kMaxRandomBytes);
|
||||
std::string out(n, '\0');
|
||||
std::FILE* f = std::fopen("/dev/urandom", "rb");
|
||||
if (!f) throw std::runtime_error("no secure random source");
|
||||
std::size_t got = std::fread(out.data(), 1, n, f);
|
||||
std::fclose(f);
|
||||
if (got != n) throw std::runtime_error("short read from urandom");
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string SecureRandom::token_hex(std::size_t n) { return to_hex(bytes(n)); }
|
||||
|
||||
namespace {
|
||||
std::string pbkdf2(const std::string& pw, const std::string& salt, int rounds) {
|
||||
std::string u = Hmac::sha256(pw, salt + std::string("\0\0\0\1", 4));
|
||||
std::string t = u;
|
||||
for (int i = 1; i < rounds; ++i) {
|
||||
u = Hmac::sha256(pw, u);
|
||||
for (std::size_t j = 0; j < t.size(); ++j) t[j] = static_cast<char>(t[j] ^ u[j]);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string PasswordHasher::hash(const std::string& password) {
|
||||
std::string salt = SecureRandom::bytes(16);
|
||||
return "pbkdf2-demo$" + std::to_string(secaps::kDemoPbkdf2Rounds) + "$" +
|
||||
to_hex(salt) + "$" +
|
||||
to_hex(pbkdf2(password, salt, secaps::kDemoPbkdf2Rounds));
|
||||
}
|
||||
|
||||
bool PasswordHasher::verify(const std::string& password, const std::string& stored) {
|
||||
std::vector<std::string> parts;
|
||||
std::size_t pos = 0;
|
||||
while (true) {
|
||||
std::size_t d = stored.find('$', pos);
|
||||
parts.push_back(stored.substr(pos, d == std::string::npos ? d : d - pos));
|
||||
if (d == std::string::npos) break;
|
||||
pos = d + 1;
|
||||
}
|
||||
if (parts.size() != 4 || parts[0] != "pbkdf2-demo") return false;
|
||||
int rounds = 0;
|
||||
try { rounds = std::stoi(parts[1]); } catch (...) { return false; }
|
||||
if (rounds < 1 || rounds > 100000) return false;
|
||||
std::string salt;
|
||||
if (!from_hex(parts[2], salt)) return false;
|
||||
return constant_time_equal(to_hex(pbkdf2(password, salt, rounds)), parts[3]);
|
||||
}
|
||||
|
||||
void DenialSink::record(const std::string& guard, const std::string& reason) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
++total_;
|
||||
if (ring_.size() >= secaps::kMaxDenials) ring_.erase(ring_.begin());
|
||||
ring_.push_back({guard, reason});
|
||||
}
|
||||
std::vector<Denial> DenialSink::list() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return ring_;
|
||||
}
|
||||
std::size_t DenialSink::total() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return total_;
|
||||
}
|
||||
|
||||
std::string CsrfGuard::issue() const {
|
||||
std::string nonce = SecureRandom::token_hex(16);
|
||||
return nonce + "." + to_hex(Hmac::sha256(secret_, nonce));
|
||||
}
|
||||
bool CsrfGuard::verify(const std::string& token) const {
|
||||
std::size_t dot = token.find('.');
|
||||
if (dot == std::string::npos || dot == 0 || token.size() > 200) return false;
|
||||
std::string nonce = token.substr(0, dot);
|
||||
return constant_time_equal(token.substr(dot + 1),
|
||||
to_hex(Hmac::sha256(secret_, nonce)));
|
||||
}
|
||||
|
||||
bool CorsPolicy::allowed(const std::string& origin) const {
|
||||
return !origin.empty() && origins_.count(origin) > 0;
|
||||
}
|
||||
bool CorsPolicy::apply_preflight(const Request& req, Response& res) const {
|
||||
std::string origin = req.headers.get("Origin");
|
||||
if (!allowed(origin)) return false;
|
||||
res.headers.set("Access-Control-Allow-Origin", origin);
|
||||
res.headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
res.headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
res.headers.set("Access-Control-Max-Age", "600");
|
||||
res.headers.set("Vary", "Origin");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RateLimiter::hit(const std::string& key, int& retry_after, int& remaining) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
auto win = std::chrono::seconds(window_);
|
||||
if (slots_.size() >= secaps::kMaxRateKeys && !slots_.count(key)) {
|
||||
for (auto it = slots_.begin(); it != slots_.end();)
|
||||
it = (now - it->second.start >= win) ? slots_.erase(it) : std::next(it);
|
||||
if (slots_.size() >= secaps::kMaxRateKeys) { // floor: refuse new keys
|
||||
retry_after = window_;
|
||||
remaining = 0;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Slot& s = slots_[key];
|
||||
if (s.count == 0 || now - s.start >= win) {
|
||||
s.start = now;
|
||||
s.count = 0;
|
||||
}
|
||||
if (s.count >= limit_) {
|
||||
auto left = std::chrono::duration_cast<std::chrono::seconds>(win - (now - s.start));
|
||||
retry_after = std::max(1, static_cast<int>(left.count()) + 1);
|
||||
remaining = 0;
|
||||
return false;
|
||||
}
|
||||
++s.count;
|
||||
retry_after = 0;
|
||||
remaining = limit_ - s.count;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::string, std::string>> SecurityHeaders::defaults() {
|
||||
return {{"X-Content-Type-Options", "nosniff"},
|
||||
{"X-Frame-Options", "DENY"},
|
||||
{"Referrer-Policy", "no-referrer"},
|
||||
{"Strict-Transport-Security", "max-age=31536000; includeSubDomains"},
|
||||
{"Cross-Origin-Opener-Policy", "same-origin"},
|
||||
{"Permissions-Policy", "camera=(), microphone=(), geolocation=()"}};
|
||||
}
|
||||
void SecurityHeaders::apply(Response& res) {
|
||||
for (const auto& [k, v] : defaults()) res.headers.set(k, v);
|
||||
}
|
||||
|
||||
CspBuilder::CspBuilder() {
|
||||
directives_["default-src"] = "'none'";
|
||||
directives_["script-src"] = "'self'";
|
||||
directives_["style-src"] = "'self'";
|
||||
directives_["img-src"] = "'self'";
|
||||
directives_["frame-ancestors"] = "'none'";
|
||||
}
|
||||
CspBuilder& CspBuilder::script_nonce(const std::string& nonce) {
|
||||
directives_["script-src"] = "'self' 'nonce-" + nonce + "'";
|
||||
return *this;
|
||||
}
|
||||
CspBuilder& CspBuilder::report_uri(const std::string& uri) {
|
||||
directives_["report-uri"] = uri;
|
||||
return *this;
|
||||
}
|
||||
CspBuilder& CspBuilder::enforce() {
|
||||
report_only_ = false;
|
||||
return *this;
|
||||
}
|
||||
std::string CspBuilder::header_name() const {
|
||||
return report_only_ ? "Content-Security-Policy-Report-Only"
|
||||
: "Content-Security-Policy";
|
||||
}
|
||||
std::string CspBuilder::build() const {
|
||||
std::string out;
|
||||
for (const auto& [k, v] : directives_) out += (out.empty() ? "" : "; ") + k + " " + v;
|
||||
return out;
|
||||
}
|
||||
|
||||
bool CspReportStore::add(const std::string& body) {
|
||||
if (body.empty() || body.size() > 4096) return false;
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
++total_;
|
||||
if (reports_.size() >= secaps::kMaxCspReports) reports_.erase(reports_.begin());
|
||||
reports_.push_back(body);
|
||||
return true;
|
||||
}
|
||||
std::vector<std::string> CspReportStore::list() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return reports_;
|
||||
}
|
||||
std::size_t CspReportStore::total() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return total_;
|
||||
}
|
||||
|
||||
PermissionGuard::PermissionGuard() {
|
||||
token_role_ = {{"viewer-token", "viewer"}, {"editor-token", "editor"},
|
||||
{"admin-token", "admin"}};
|
||||
role_perms_["viewer"] = {"doc:read"};
|
||||
role_perms_["editor"] = {"doc:read", "doc:write"};
|
||||
role_perms_["admin"] = {"doc:read", "doc:write", "admin:manage"};
|
||||
}
|
||||
PermissionGuard::Verdict PermissionGuard::check(const std::string& authorization,
|
||||
const std::string& permission,
|
||||
std::string& role) const {
|
||||
role.clear();
|
||||
const std::string prefix = "Bearer ";
|
||||
if (authorization.compare(0, prefix.size(), prefix) != 0)
|
||||
return Verdict::Unauthenticated;
|
||||
auto it = token_role_.find(authorization.substr(prefix.size()));
|
||||
if (it == token_role_.end()) return Verdict::Unauthenticated;
|
||||
role = it->second;
|
||||
return role_perms_.at(role).count(permission) ? Verdict::Allow
|
||||
: Verdict::Forbidden;
|
||||
}
|
||||
std::vector<std::string> PermissionGuard::permissions(const std::string& role) const {
|
||||
auto it = role_perms_.find(role);
|
||||
if (it == role_perms_.end()) return {};
|
||||
return {it->second.begin(), it->second.end()};
|
||||
}
|
||||
|
||||
SecretsProvider::SecretsProvider() {
|
||||
values_ = {{"DB_PASSWORD", "demo-db-password-1234"},
|
||||
{"API_KEY", "demo-api-key-abcdef"},
|
||||
{"SIGNING_KEY", "demo-signing-key-zz"}};
|
||||
}
|
||||
std::vector<std::string> SecretsProvider::names() const {
|
||||
std::vector<std::string> out;
|
||||
for (const auto& [k, v] : values_) out.push_back(k);
|
||||
return out;
|
||||
}
|
||||
bool SecretsProvider::masked(const std::string& name, std::string& out) const {
|
||||
auto it = values_.find(name);
|
||||
if (it == values_.end()) return false;
|
||||
const std::string& v = it->second;
|
||||
out = v.substr(0, 2) + std::string(v.size() - 4, '*') + v.substr(v.size() - 2);
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace {
|
||||
std::string lower(std::string s) {
|
||||
for (auto& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
|
||||
return s;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string SqlSafety::check(const std::string& value) {
|
||||
std::string v = lower(value);
|
||||
for (const char* bad : {"--", ";", "/*", "' or ", "\" or ", "union select",
|
||||
"drop table", "xp_"})
|
||||
if (v.find(bad) != std::string::npos)
|
||||
return std::string("SQL metacharacter or keyword rejected: ") + bad;
|
||||
return "";
|
||||
}
|
||||
std::string PathGuard::check(const std::string& value) {
|
||||
std::string v = lower(value);
|
||||
if (v.find('\0') != std::string::npos) return "NUL byte rejected";
|
||||
if (!v.empty() && v[0] == '/') return "absolute path rejected";
|
||||
for (const char* bad : {"..", "%2e", "\\"})
|
||||
if (v.find(bad) != std::string::npos)
|
||||
return std::string("traversal sequence rejected: ") + bad;
|
||||
return "";
|
||||
}
|
||||
|
||||
std::string UploadValidator::check(const std::string& filename,
|
||||
const std::string& bytes) {
|
||||
if (filename.empty() || filename.size() > 255) return "file name length must be 1 to 255";
|
||||
if (filename.find('/') != std::string::npos ||
|
||||
filename.find('\\') != std::string::npos || filename.find("..") != std::string::npos)
|
||||
return "file name must not contain path parts";
|
||||
std::size_t dot = filename.rfind('.');
|
||||
if (dot == std::string::npos) return "extension not allowed (use pdf, png, txt)";
|
||||
std::string ext = lower(filename.substr(dot + 1));
|
||||
if (ext != "pdf" && ext != "png" && ext != "txt")
|
||||
return "extension not allowed (use pdf, png, txt)";
|
||||
if (bytes.size() > kMaxFileBytes) return "file too large (max 1024 bytes)";
|
||||
if (bytes.empty()) return "file is empty";
|
||||
if (ext == "pdf" && bytes.compare(0, 5, "%PDF-") != 0)
|
||||
return "content does not match pdf magic bytes";
|
||||
if (ext == "png" && bytes.compare(0, 4, "\x89PNG") != 0)
|
||||
return "content does not match png magic bytes";
|
||||
if (ext == "txt")
|
||||
for (unsigned char c : bytes)
|
||||
if (c < 9 || (c > 13 && c < 32) || c == 127)
|
||||
return "txt content contains binary bytes";
|
||||
return "";
|
||||
}
|
||||
|
||||
} // namespace molo::example::fw
|
||||
@@ -0,0 +1,201 @@
|
||||
#pragma once
|
||||
|
||||
// SecurityExtra framework skeleton for the living example (namespace
|
||||
// molo::example::fw). Mirrors names and behavior of src/security/{guard,
|
||||
// crypto,auth,secret,upload} and src/cli/csp in small, readable form.
|
||||
// Every container has a hard cap. Crypto here is real SHA-256/HMAC but the
|
||||
// password hasher uses DEMO iteration counts: not for production use.
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "Http.hpp"
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
namespace secaps {
|
||||
inline constexpr std::size_t kMaxDenials = 100;
|
||||
inline constexpr std::size_t kMaxRateKeys = 1024;
|
||||
inline constexpr std::size_t kMaxCspReports = 50;
|
||||
inline constexpr std::size_t kMaxRandomBytes = 64;
|
||||
inline constexpr std::size_t kMaxHashInput = 4096;
|
||||
inline constexpr std::size_t kMaxUploadHex = 4096;
|
||||
inline constexpr std::size_t kMaxInputLen = 512;
|
||||
inline constexpr int kDemoPbkdf2Rounds = 2000; // real: 600000+
|
||||
} // namespace secaps
|
||||
|
||||
std::string to_hex(const std::string& raw);
|
||||
bool from_hex(const std::string& hex, std::string& raw);
|
||||
bool constant_time_equal(const std::string& a, const std::string& b);
|
||||
|
||||
// Mirrors src/security/crypto/Sha256.h and Hmac.h.
|
||||
class Sha256 {
|
||||
public:
|
||||
static std::string digest(const std::string& data); // 32 raw bytes
|
||||
static std::string hex(const std::string& data);
|
||||
};
|
||||
|
||||
class Hmac {
|
||||
public:
|
||||
static std::string sha256(const std::string& key, const std::string& data);
|
||||
};
|
||||
|
||||
// Mirrors SecureRandom.h: /dev/urandom, capped length.
|
||||
class SecureRandom {
|
||||
public:
|
||||
static std::string bytes(std::size_t n);
|
||||
static std::string token_hex(std::size_t n);
|
||||
};
|
||||
|
||||
// Mirrors PasswordHasher.h with PBKDF2-HMAC-SHA256 at demo rounds.
|
||||
class PasswordHasher {
|
||||
public:
|
||||
static std::string hash(const std::string& password); // "pbkdf2$r$salt$dk"
|
||||
static bool verify(const std::string& password, const std::string& stored);
|
||||
};
|
||||
|
||||
// Mirrors guard/DenialSink.h: capped ring of why requests were refused.
|
||||
struct Denial {
|
||||
std::string guard;
|
||||
std::string reason;
|
||||
};
|
||||
class DenialSink {
|
||||
public:
|
||||
void record(const std::string& guard, const std::string& reason);
|
||||
std::vector<Denial> list() const;
|
||||
std::size_t total() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::vector<Denial> ring_;
|
||||
std::size_t total_ = 0;
|
||||
};
|
||||
|
||||
// Mirrors guard/CsrfGuard.h: stateless signed token "nonce.mac".
|
||||
class CsrfGuard {
|
||||
public:
|
||||
explicit CsrfGuard(std::string secret) : secret_(std::move(secret)) {}
|
||||
std::string issue() const;
|
||||
bool verify(const std::string& token) const;
|
||||
|
||||
private:
|
||||
std::string secret_;
|
||||
};
|
||||
|
||||
// Mirrors guard/CorsPolicy.h: exact-origin allowlist, no wildcard with creds.
|
||||
class CorsPolicy {
|
||||
public:
|
||||
explicit CorsPolicy(std::set<std::string> origins)
|
||||
: origins_(std::move(origins)) {}
|
||||
bool allowed(const std::string& origin) const;
|
||||
// Fills Access-Control-* headers when the origin is allowed.
|
||||
bool apply_preflight(const Request& req, Response& res) const;
|
||||
|
||||
private:
|
||||
std::set<std::string> origins_;
|
||||
};
|
||||
|
||||
// Mirrors guard/RateLimiter.h: fixed window per key, capped key table.
|
||||
class RateLimiter {
|
||||
public:
|
||||
RateLimiter(int limit, int window_seconds)
|
||||
: limit_(limit), window_(window_seconds) {}
|
||||
// Returns true when allowed; else sets retry_after (seconds, >= 1).
|
||||
bool hit(const std::string& key, int& retry_after, int& remaining);
|
||||
int limit() const { return limit_; }
|
||||
int window() const { return window_; }
|
||||
|
||||
private:
|
||||
struct Slot {
|
||||
std::chrono::steady_clock::time_point start;
|
||||
int count = 0;
|
||||
};
|
||||
std::mutex mu_;
|
||||
std::map<std::string, Slot> slots_;
|
||||
int limit_;
|
||||
int window_;
|
||||
};
|
||||
|
||||
// Mirrors guard/SecurityHeaders.h.
|
||||
class SecurityHeaders {
|
||||
public:
|
||||
static std::vector<std::pair<std::string, std::string>> defaults();
|
||||
static void apply(Response& res);
|
||||
};
|
||||
|
||||
// Mirrors src/cli/csp: builder, per-request nonce, capped report store.
|
||||
class CspBuilder {
|
||||
public:
|
||||
CspBuilder();
|
||||
CspBuilder& script_nonce(const std::string& nonce);
|
||||
CspBuilder& report_uri(const std::string& uri);
|
||||
CspBuilder& enforce();
|
||||
std::string header_name() const;
|
||||
std::string build() const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::string> directives_;
|
||||
bool report_only_ = true;
|
||||
};
|
||||
class CspReportStore {
|
||||
public:
|
||||
bool add(const std::string& body); // false when body is empty/too large
|
||||
std::vector<std::string> list() const;
|
||||
std::size_t total() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::vector<std::string> reports_;
|
||||
std::size_t total_ = 0;
|
||||
};
|
||||
|
||||
// Mirrors auth/Permission.h + Guard.h: token -> role -> permission set.
|
||||
class PermissionGuard {
|
||||
public:
|
||||
PermissionGuard();
|
||||
enum class Verdict { Allow, Unauthenticated, Forbidden };
|
||||
Verdict check(const std::string& authorization,
|
||||
const std::string& permission, std::string& role) const;
|
||||
std::vector<std::string> permissions(const std::string& role) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::string> token_role_;
|
||||
std::map<std::string, std::set<std::string>> role_perms_;
|
||||
};
|
||||
|
||||
// Mirrors secret/SecretsProvider.h; values never leave except masked.
|
||||
class SecretsProvider {
|
||||
public:
|
||||
SecretsProvider();
|
||||
std::vector<std::string> names() const;
|
||||
bool masked(const std::string& name, std::string& out) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::string> values_;
|
||||
};
|
||||
|
||||
// Mirrors guard/SqlSafety.h and PathGuard.h: returns "" when safe, else reason.
|
||||
class SqlSafety {
|
||||
public:
|
||||
static std::string check(const std::string& value);
|
||||
};
|
||||
class PathGuard {
|
||||
public:
|
||||
static std::string check(const std::string& value);
|
||||
};
|
||||
|
||||
// Mirrors upload/UploadValidator.h: ext allowlist, size cap, magic bytes.
|
||||
class UploadValidator {
|
||||
public:
|
||||
static constexpr std::size_t kMaxFileBytes = 1024;
|
||||
static std::string check(const std::string& filename,
|
||||
const std::string& bytes); // "" when allowed
|
||||
};
|
||||
|
||||
} // namespace molo::example::fw
|
||||
@@ -0,0 +1,21 @@
|
||||
// Route: GET/POST /audit/log (hash-chained log page and append form)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto page = f.client->get("/audit/log");
|
||||
check(page.status == 200 && contains(page.headers.get("Content-Type"), "text/html"), "html page");
|
||||
check(contains(page.body, "Chain intact"), "intact");
|
||||
auto js = f.client->request(Method::Get, "/audit/log", "", {{"Accept", "application/json"}});
|
||||
check(contains(js.body, "\"records\""), "json variant");
|
||||
auto bad = f.client->post("/audit/log", "actor=&action=x&subject=y", "application/x-www-form-urlencoded");
|
||||
check(bad.status == 422 && contains(bad.body, "field-error"), "inline validation");
|
||||
auto ok = f.client->post("/audit/log", "actor=ada&action=edit&subject=doc&detail=mail+me%40example.com", "application/x-www-form-urlencoded");
|
||||
check(ok.status == 201 && contains(ok.body, "appended"), "appended");
|
||||
auto after = f.client->request(Method::Get, "/audit/log", "", {{"Accept", "application/json"}});
|
||||
check(contains(after.body, "[EMAIL]") && !contains(after.body, "me@example.com"), "side effect: PII redacted in record");
|
||||
return finish("audit/log");
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Route: GET /audit/mask (masking and redaction patterns)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto d = f.client->get("/audit/mask");
|
||||
check(d.status == 200 && contains(d.body, "a***********@example.com"), "email masked");
|
||||
check(contains(d.body, "************1111"), "card keeps last 4");
|
||||
check(contains(d.body, "[EMAIL]") && contains(d.body, "[SSN]") && contains(d.body, "[IP]"), "redactions");
|
||||
check(contains(d.body, "\"redactions\":4"), "counted 4 hits");
|
||||
auto c = f.client->get("/audit/mask?text=nothing+here");
|
||||
check(contains(c.body, "\"redactions\":0"), "clean text unchanged");
|
||||
check(f.client->post("/audit/mask").status == 405, "405");
|
||||
return finish("audit/mask");
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Route: GET /audit/retention + hold + purge (policy, legal hold, dry run)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto page = f.client->get("/audit/retention");
|
||||
check(page.status == 200 && contains(page.body, "expired"), "html page");
|
||||
auto js = f.client->request(Method::Get, "/audit/retention", "", {{"Accept", "application/json"}});
|
||||
check(contains(js.body, "\"r1\"") && contains(js.body, "\"r5\""), "expired listed");
|
||||
auto dry = f.client->post("/audit/retention/purge", "");
|
||||
check(contains(dry.body, "\"dry_run\":true") && contains(dry.body, "\"purged\":0"), "dry run by default");
|
||||
check(f.client->post("/audit/retention/hold", "id=r1&hold=true").status == 200, "hold");
|
||||
auto real = f.client->post("/audit/retention/purge", "confirm=yes");
|
||||
check(contains(real.body, "\"purged\":2"), "held entry skipped, two purged");
|
||||
auto after = f.client->request(Method::Get, "/audit/retention", "", {{"Accept", "application/json"}});
|
||||
check(contains(after.body, "\"r1\"") && !contains(after.body, "\"id\":\"r5\""), "side effect: r1 kept, r5 gone");
|
||||
check(f.client->post("/audit/retention/hold", "id=r1&hold=x").status == 422, "bad hold");
|
||||
check(f.client->post("/audit/retention/hold", "id=zz&hold=true").status == 404, "unknown id");
|
||||
return finish("audit/retention");
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Route: GET /audit/subject, export, POST erase (data subject rights)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto page = f.client->get("/audit/subject");
|
||||
check(page.status == 200 && contains(page.headers.get("Content-Type"), "text/html"), "form page");
|
||||
auto ex = f.client->get("/audit/subject/export?subject=ada@example.com");
|
||||
check(ex.status == 200 && contains(ex.body, "order=1001") && contains(ex.body, "profiles"), "export across tables");
|
||||
check(f.client->get("/audit/subject/export").status == 400, "missing subject");
|
||||
auto bad = f.client->post("/audit/subject/erase", "subject=nope&confirm=no", "application/x-www-form-urlencoded");
|
||||
check(bad.status == 422 && contains(bad.body, "field-error"), "inline errors");
|
||||
auto ok = f.client->post("/audit/subject/erase", "subject=ada%40example.com&confirm=yes", "application/x-www-form-urlencoded");
|
||||
check(ok.status == 200 && contains(ok.body, "4 rows erased"), "cascade erased 4 rows");
|
||||
check(!contains(f.client->get("/audit/subject/export?subject=ada@example.com").body, "order="), "side effect: data gone");
|
||||
check(contains(f.client->get("/audit/verify").body, "\"intact\":true"), "erasure audited, chain intact");
|
||||
return finish("audit/subject");
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Route: GET /audit/verify + POST /audit/tamper (tamper detection)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto v = f.client->get("/audit/verify");
|
||||
check(v.status == 200 && contains(v.body, "\"intact\":true") && contains(v.body, "\"first_broken\":null"), "intact");
|
||||
check(f.client->post("/audit/tamper", "index=abc").status == 422, "bad index");
|
||||
check(f.client->post("/audit/tamper", "index=99").status == 404, "missing record");
|
||||
check(f.client->post("/audit/tamper", "index=1").status == 200, "tamper");
|
||||
auto b = f.client->get("/audit/verify");
|
||||
check(contains(b.body, "\"intact\":false") && contains(b.body, "\"first_broken\":1"), "first broken index reported");
|
||||
check(contains(f.client->get("/audit/log").body, "Chain broken at index 1"), "side effect: page shows break");
|
||||
return finish("audit/verify");
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Route: GET /cli/commands (real molo command reference)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto res = f.client->get("/cli/commands");
|
||||
check(res.status == 200 && contains(res.headers.get("Content-Type"), "text/html"), "html page");
|
||||
for (const char* c : {"new", "serve", "build", "embed", "migrate", "health", "supervisor", "task",
|
||||
"ai", "expose", "verify", "supply-check", "release", "rollout", "rollback",
|
||||
"experiment", "debug"})
|
||||
check(contains(res.body, std::string("<code>molo ") + c + "</code>"), std::string("lists ") + c);
|
||||
auto js = f.client->request(Method::Get, "/cli/commands", "", {{"Accept", "application/json"}});
|
||||
check(contains(js.body, "\"commands\""), "json for json clients");
|
||||
check(f.services.features.size() > 0, "side effect: feature rows registered");
|
||||
check(f.client->request(Method::Post, "/cli/commands").status == 405, "post is 405");
|
||||
return finish("clicmd/commands");
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Route: /clients/retry (capped backoff, 4xx never retried)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/clients/retry").status == 200, "status 200");
|
||||
auto ok = f.client->post("/clients/retry/run", "failures=2&max_attempts=3&status=503", kForm);
|
||||
check(contains(ok.body, "final status 200 after 3 attempt(s)"), "succeeds on third attempt");
|
||||
check(contains(ok.body, "backoff 100ms") && contains(ok.body, "backoff 200ms"), "doubling backoff");
|
||||
auto cap = f.client->post("/clients/retry/run", "failures=10&max_attempts=5&status=503", kForm);
|
||||
check(contains(cap.body, "final status 503 after 5 attempt(s)"), "gives up at the attempt cap");
|
||||
check(contains(cap.body, "backoff 800ms"), "backoff capped at 800ms");
|
||||
auto c4 = f.client->post("/clients/retry/run", "failures=3&max_attempts=5&status=404", kForm);
|
||||
check(contains(c4.body, "after 1 attempt(s)"), "404 is not retried");
|
||||
auto bad = f.client->post("/clients/retry/run", "failures=1&max_attempts=9&status=200", kForm);
|
||||
check(bad.status == 422 && contains(bad.body, "must be between 1 and 5"), "422 attempts above hard cap");
|
||||
check(contains(f.client->get("/clients/retry").body, "runs"), "side effect: runs counted");
|
||||
return finish("clients/retry");
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Route: /clients/session (cookie jar, pool, proxy, auth)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/clients/session").status == 200, "status 200");
|
||||
auto r1 = f.client->post("/clients/session/request", "auth=basic", kForm);
|
||||
check(contains(r1.body, "Authorization=Basic ZGVtbzpkZW1v"), "basic auth header");
|
||||
check(!contains(r1.body, "Cookie="), "first request has no cookie");
|
||||
auto r2 = f.client->post("/clients/session/request", "auth=bearer", kForm);
|
||||
check(contains(r2.body, "Cookie=sid=s-1; visits=1"), "cookie jar replays server cookies");
|
||||
check(contains(r2.body, "Bearer demo-token"), "bearer header");
|
||||
check(contains(r2.body, "connection reused"), "pooled connection reused");
|
||||
auto r3 = f.client->post("/clients/session/request", "proxy=http://proxy.local:3128", kForm);
|
||||
check(contains(r3.body, "connection created via http://proxy.local:3128"), "proxy change opens new connection");
|
||||
auto bad = f.client->post("/clients/session/request", "proxy=ftp://x", kForm);
|
||||
check(bad.status == 422 && contains(bad.body, "socks5://host:port"), "422 bad proxy");
|
||||
auto badauth = f.client->post("/clients/session/request", "auth=digest", kForm);
|
||||
check(badauth.status == 422, "422 unknown auth");
|
||||
check(contains(f.client->get("/clients/session").body, "pool_created"), "side effect: pool stats shown");
|
||||
return finish("clients/session");
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Route: GET /compress/demo (gzip negotiated by Accept-Encoding)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto plain = f.client->get("/compress/demo?size=1000");
|
||||
check(plain.status == 200 && plain.body.size() == 1000, "identity body");
|
||||
check(!plain.headers.has("Content-Encoding"), "no encoding without header");
|
||||
auto gz = f.client->request(Method::Get, "/compress/demo?size=1000", "", {{"Accept-Encoding", "br, gzip;q=0.8"}});
|
||||
check(gz.headers.get("Content-Encoding") == "gzip", "content-encoding gzip");
|
||||
check(gz.body.size() > 2 && (unsigned char)gz.body[0] == 0x1f && (unsigned char)gz.body[1] == 0x8b, "gzip magic");
|
||||
check(gz.headers.get("Vary") == "Accept-Encoding", "vary");
|
||||
check(gz.headers.get("X-Original-Length") == "1000", "original length header");
|
||||
auto refused = f.client->request(Method::Get, "/compress/demo?size=1000", "", {{"Accept-Encoding", "gzip;q=0"}});
|
||||
check(!refused.headers.has("Content-Encoding"), "q=0 refuses gzip");
|
||||
auto tiny = f.client->request(Method::Get, "/compress/demo?size=10", "", {{"Accept-Encoding", "gzip"}});
|
||||
check(!tiny.headers.has("Content-Encoding"), "tiny bodies stay identity");
|
||||
check(f.client->get("/compress/demo?size=x").status == 422, "bad size 422");
|
||||
check(f.client->get("/compress/demo?size=9999999").status == 422, "size cap 422");
|
||||
check(f.client->request(Method::Post, "/compress/demo").status == 405, "post is 405");
|
||||
return finish("compress/demo");
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Route: GET/POST /conditional/doc (ETag, 304, Range, If-Match)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto full = f.client->get("/conditional/doc");
|
||||
std::string etag = full.headers.get("ETag");
|
||||
check(full.status == 200 && !etag.empty(), "200 with etag");
|
||||
check(full.headers.get("Accept-Ranges") == "bytes", "accept-ranges");
|
||||
auto nm = f.client->request(Method::Get, "/conditional/doc", "", {{"If-None-Match", etag}});
|
||||
check(nm.status == 304 && nm.body.empty(), "304 on matching etag");
|
||||
auto weak = f.client->request(Method::Get, "/conditional/doc", "", {{"If-None-Match", "W/" + etag}});
|
||||
check(weak.status == 304, "weak tag matches");
|
||||
auto part = f.client->request(Method::Get, "/conditional/doc", "", {{"Range", "bytes=0-9"}});
|
||||
check(part.status == 206 && part.body == full.body.substr(0, 10), "206 partial body");
|
||||
check(part.headers.get("Content-Range") == "bytes 0-9/" + std::to_string(full.body.size()), "content-range");
|
||||
auto suffix = f.client->request(Method::Get, "/conditional/doc", "", {{"Range", "bytes=-4"}});
|
||||
check(suffix.body == full.body.substr(full.body.size() - 4), "suffix range");
|
||||
auto bad = f.client->request(Method::Get, "/conditional/doc", "", {{"Range", "bytes=99999-"}});
|
||||
check(bad.status == 416, "416 unsatisfiable");
|
||||
auto stale = f.client->request(Method::Post, "/conditional/doc", "new text", {{"If-Match", "\"nope\""}});
|
||||
check(stale.status == 412, "412 on stale If-Match");
|
||||
auto ok = f.client->request(Method::Post, "/conditional/doc", "new text", {{"If-Match", etag}});
|
||||
check(ok.status == 200, "update with matching If-Match");
|
||||
auto after = f.client->get("/conditional/doc");
|
||||
check(after.body == "new text" && after.headers.get("ETag") != etag, "side effect: new body and etag");
|
||||
check(f.client->request(Method::Post, "/conditional/doc", "").status == 422, "empty body 422");
|
||||
check(f.client->request(Method::Post, "/conditional/doc", std::string(5000, 'x')).status == 413, "over cap 413");
|
||||
check(f.client->request(Method::Delete, "/conditional/doc").status == 405, "delete is 405");
|
||||
return finish("conditional/doc");
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Route: GET /context/trace (traceparent continuation, correlation id)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
std::string tid = "4bf92f3577b34da6a3ce929d0e0e4736";
|
||||
auto cont = f.client->request(Method::Get, "/context/trace", "",
|
||||
{{"traceparent", "00-" + tid + "-00f067aa0ba902b7-01"}, {"X-Correlation-ID", "corr-9"}});
|
||||
check(cont.status == 200, "status 200");
|
||||
check(contains(cont.body, "\"trace_id\":\"" + tid), "trace id continued");
|
||||
check(contains(cont.body, "\"parent_span_id\":\"00f067aa0ba902b7\""), "parent span reported");
|
||||
check(cont.headers.get("traceparent").rfind("00-" + tid + "-", 0) == 0, "response traceparent same trace");
|
||||
check(!contains(cont.headers.get("traceparent"), "00f067aa0ba902b7"), "new span id");
|
||||
check(cont.headers.get("X-Correlation-ID") == "corr-9", "correlation propagated");
|
||||
auto fresh = f.client->get("/context/trace");
|
||||
check(contains(fresh.body, "\"continued\":false") && contains(fresh.body, "\"parent_valid\":true"), "new trace");
|
||||
check(fresh.headers.get("X-Correlation-ID").rfind("req-", 0) == 0, "falls back to request id");
|
||||
auto bad = f.client->request(Method::Get, "/context/trace", "", {{"traceparent", "garbage"}});
|
||||
check(contains(bad.body, "\"parent_valid\":false") && contains(bad.body, "\"continued\":false"), "invalid parent restarts trace");
|
||||
check(f.client->request(Method::Post, "/context/trace").status == 405, "post is 405");
|
||||
return finish("context/trace");
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Route: /crypto/hash (real SHA-256 and HMAC-SHA256)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(contains(f.client->get("/crypto/hash").body, "<form"), "form renders");
|
||||
auto r = f.client->post("/crypto/hash", "text=abc", kForm);
|
||||
check(r.status == 200, "status 200");
|
||||
check(contains(r.body, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"), "sha256(abc) vector");
|
||||
auto m = f.client->post("/crypto/hash", "text=what+do+ya+want+for+nothing%3F&key=Jefe", kForm);
|
||||
check(contains(m.body, "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"), "RFC 4231 hmac vector");
|
||||
auto bad = f.client->post("/crypto/hash", "text=", kForm);
|
||||
check(bad.status == 422 && contains(bad.body, "form-errors"), "empty text inline 422");
|
||||
auto big = f.client->post("/crypto/hash", "text=" + std::string(5000, 'a'), kForm);
|
||||
check(big.status == 422, "over cap 422");
|
||||
check(f.client->request(molo::example::fw::Method::Put, "/crypto/hash").status == 405, "PUT is 405");
|
||||
return finish("crypto/hash");
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Route: /crypto/password (salted PBKDF2, demo rounds)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(contains(f.client->get("/crypto/password").body, "DEMO"), "labelled demo");
|
||||
auto a = f.client->post("/crypto/password", "password=correct-horse", kForm);
|
||||
auto b = f.client->post("/crypto/password", "password=correct-horse", kForm);
|
||||
check(a.status == 200 && contains(a.body, "pbkdf2-demo$2000$"), "hash format");
|
||||
check(contains(a.body, "verify ok: yes") && contains(a.body, "wrong password: rejected"), "verify works");
|
||||
auto salt = [](const std::string& s) { std::size_t p = s.find("pbkdf2-demo$2000$"); return s.substr(p + 17, 32); };
|
||||
check(salt(a.body) != salt(b.body), "salt differs per hash");
|
||||
auto bad = f.client->post("/crypto/password", "password=short", kForm);
|
||||
check(bad.status == 422 && contains(bad.body, "must be 8 to 128"), "short password inline 422");
|
||||
check(f.client->post("/crypto/password", "password=" + std::string(129, 'a'), kForm).status == 422, "over cap 422");
|
||||
return finish("crypto/password");
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Route: GET /crypto/random (urandom token, 1 to 64 bytes)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto a = f.client->get("/crypto/random?bytes=8");
|
||||
auto b = f.client->get("/crypto/random?bytes=8");
|
||||
check(a.status == 200 && contains(a.body, "\"bytes\":8"), "8 bytes ok");
|
||||
check(a.body != b.body, "tokens differ");
|
||||
check(f.client->get("/crypto/random").status == 200, "default ok");
|
||||
check(f.client->get("/crypto/random?bytes=65").status == 400, "over cap 400");
|
||||
check(f.client->get("/crypto/random?bytes=abc").status == 400, "non numeric 400");
|
||||
check(f.client->post("/crypto/random", "x").status == 405, "POST 405");
|
||||
return finish("crypto/random");
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Route: GET /csp/page (per-request nonce in header and script tag)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
static std::string nonce_of(const std::string& h) {
|
||||
std::size_t a = h.find("'nonce-");
|
||||
if (a == std::string::npos) return "";
|
||||
a += 7;
|
||||
return h.substr(a, h.find('\'', a) - a);
|
||||
}
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto a = f.client->get("/csp/page");
|
||||
auto b = f.client->get("/csp/page");
|
||||
check(a.status == 200 && contains(a.content_type(), "text/html"), "html 200");
|
||||
std::string h = a.headers.get("Content-Security-Policy-Report-Only");
|
||||
check(contains(h, "default-src 'none'"), "deny-first default");
|
||||
check(contains(h, "report-uri /csp/report"), "report uri set");
|
||||
std::string n = nonce_of(h);
|
||||
check(n.size() == 32, "nonce is 16 random bytes in hex");
|
||||
check(contains(a.body, "<script nonce=\"" + n + "\">"), "script carries same nonce");
|
||||
check(n != nonce_of(b.headers.get("Content-Security-Policy-Report-Only")), "nonce differs per request");
|
||||
check(f.client->post("/csp/page", "x").status == 405, "POST is 405");
|
||||
return finish("csp/page");
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Route: /csp/report (violation report intake, capped store)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto ok = f.client->post("/csp/report", "{\"csp-report\":{\"blocked-uri\":\"inline\"}}", "application/csp-report");
|
||||
check(ok.status == 204, "report accepted 204");
|
||||
auto empty = f.client->post("/csp/report", "", "application/csp-report");
|
||||
check(empty.status == 400, "empty report is 400");
|
||||
auto big = f.client->post("/csp/report", std::string(5000, 'x'), "application/csp-report");
|
||||
check(big.status == 400, "oversized report is 400");
|
||||
for (int i = 0; i < 60; ++i) f.client->post("/csp/report", "r", "application/csp-report");
|
||||
auto list = f.client->get("/csp/report");
|
||||
check(list.status == 200 && contains(list.body, "\"total\":61"), "total counted");
|
||||
std::size_t n = 0, p = 0;
|
||||
while ((p = list.body.find("\"r\"", p)) != std::string::npos) { ++n; p += 3; }
|
||||
check(n <= 50, "stored reports capped at 50");
|
||||
return finish("csp/report");
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// Route: /data/migrations (check preview, apply, drift, heal)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto page = f.client->get("/data/migrations");
|
||||
check(page.status == 200, "status 200");
|
||||
check(contains(page.body, "CREATE TABLE users") && contains(page.body, "CREATE TABLE posts"), "preview lists pending sql");
|
||||
check(contains(page.body, "none"), "nothing applied by viewing");
|
||||
auto one = f.client->post("/data/migrations/apply", "limit=1", kForm);
|
||||
check(contains(one.body, "1 migration(s) applied"), "apply one step");
|
||||
check(!contains(one.body, "CREATE TABLE users"), "applied step leaves the preview");
|
||||
check(contains(one.body, "CREATE TABLE posts"), "later steps still pending");
|
||||
auto rest = f.client->post("/data/migrations/apply", "limit=3", kForm);
|
||||
check(contains(rest.body, "2 migration(s) applied"), "rest applied");
|
||||
check(contains(rest.body, "table posts"), "side effect: table exists");
|
||||
f.client->post("/data/migrations/drift", "", kForm);
|
||||
check(contains(f.client->get("/data/migrations").body, "003 posts"), "drift detected");
|
||||
check(contains(f.client->post("/data/migrations/heal", "", kForm).body, "1 table(s) healed"), "healer repairs drift");
|
||||
auto bad = f.client->post("/data/migrations/apply", "limit=9", kForm);
|
||||
check(bad.status == 422 && contains(bad.body, "must be between 1 and 3"), "422 step limit");
|
||||
return finish("data/migrations");
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Route: /data/query (query builder and has-many relation)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/data/query").status == 200, "status 200");
|
||||
auto all = f.client->post("/data/query/run", "limit=10&order=title", kForm);
|
||||
check(contains(all.body, "ORDER BY posts.title LIMIT 10"), "sql built");
|
||||
check(contains(all.body, "5 row(s)"), "five posts");
|
||||
check(contains(all.body, "Alpha by ada") && contains(all.body, "Beta by grace"), "relation joins author");
|
||||
auto ada = f.client->post("/data/query/run", "user_id=1", kForm);
|
||||
check(contains(ada.body, "WHERE posts.user_id = 1") && contains(ada.body, "3 row(s)"), "where filter");
|
||||
auto lim = f.client->post("/data/query/run", "limit=2", kForm);
|
||||
check(contains(lim.body, "2 row(s)"), "limit applied");
|
||||
auto bad = f.client->post("/data/query/run", "order=name", kForm);
|
||||
check(bad.status == 422 && contains(bad.body, "must be one of: id, title"), "422 order whitelist");
|
||||
check(f.client->post("/data/query/run", "limit=99", kForm).status == 422, "422 limit above cap");
|
||||
return finish("data/query");
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Route: /data/singleflight (concurrent loads collapse into one)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/data/singleflight").status == 200, "status 200");
|
||||
auto res = f.client->post("/data/singleflight/run", "callers=8", kForm);
|
||||
check(contains(res.body, "8 callers, 1 load(s)"), "eight callers share one load");
|
||||
auto one = f.client->post("/data/singleflight/run", "callers=1", kForm);
|
||||
check(contains(one.body, "1 callers, 1 load(s)"), "single caller loads once");
|
||||
auto max = f.client->post("/data/singleflight/run", "callers=16", kForm);
|
||||
check(contains(max.body, "16 callers, 1 load(s)"), "cap of 16 threads still collapses");
|
||||
auto bad = f.client->post("/data/singleflight/run", "callers=17", kForm);
|
||||
check(bad.status == 422 && contains(bad.body, "must be between 1 and 16"), "422 above thread cap");
|
||||
check(contains(f.client->get("/data/singleflight").body, ">3<"), "side effect: three runs counted");
|
||||
return finish("data/singleflight");
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Route: /data/transaction (commit and rollback)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/data/transaction").status == 200, "status 200");
|
||||
auto ok = f.client->post("/data/transaction/transfer", "amount=30", kForm);
|
||||
check(contains(ok.body, "committed"), "commit");
|
||||
check(f.services.sqlite != nullptr, "fixture alive");
|
||||
auto fail = f.client->post("/data/transaction/transfer", "amount=10&fail_after_debit=1", kForm);
|
||||
check(contains(fail.body, "rolled back: failure after debit"), "failure rolls back");
|
||||
auto over = f.client->post("/data/transaction/transfer", "amount=500", kForm);
|
||||
check(contains(over.body, "rolled back: insufficient funds"), "overdraft rolls back");
|
||||
auto json = f.client->request(Method::Post, "/data/transaction/transfer", "{\"amount\":\"1\"}", {{"Content-Type", "application/json"}});
|
||||
check(json.status == 200 && contains(json.body, "\"alice\":\"69\""), "alice 100-30-1; rollbacks changed nothing");
|
||||
check(contains(json.body, "\"rollbacks\":\"2\"") && contains(json.body, "\"commits\":\"2\""), "side effect: counters");
|
||||
auto same = f.client->post("/data/transaction/transfer", "from=bob&to=bob&amount=5", kForm);
|
||||
check(same.status == 422 && contains(same.body, "must differ"), "422 same account");
|
||||
check(f.client->post("/data/transaction/transfer", "amount=0", kForm).status == 422, "422 amount limit");
|
||||
return finish("data/transaction");
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Route: /data/ttl (TTL expiry, LRU eviction, pubsub events)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/data/ttl").status == 200, "status 200");
|
||||
f.client->post("/data/ttl/set", "key=a&value=1&ttl_s=5", kForm);
|
||||
check(contains(f.client->post("/data/ttl/get", "key=a", kForm).body, "hit: 1"), "hit");
|
||||
f.client->post("/data/ttl/tick", "", kForm);
|
||||
auto gone = f.client->post("/data/ttl/get", "key=a", kForm);
|
||||
check(contains(gone.body, "miss") && contains(gone.body, "expired a"), "expired after ttl, event published");
|
||||
for (int i = 0; i < 6; ++i)
|
||||
f.client->post("/data/ttl/set", "key=k" + std::to_string(i) + "&value=v&ttl_s=60", kForm);
|
||||
auto page = f.client->get("/data/ttl");
|
||||
check(contains(page.body, "5/5"), "capacity capped at 5");
|
||||
check(contains(page.body, "evicted k0 (lru)"), "oldest key evicted");
|
||||
auto bad = f.client->post("/data/ttl/set", "key=&value=x&ttl_s=0", kForm);
|
||||
check(bad.status == 422 && contains(bad.body, "is required"), "422 missing key");
|
||||
check(f.client->post("/data/ttl/set", "key=a&value=b&ttl_s=999", kForm).status == 422, "422 ttl above cap");
|
||||
return finish("data/ttl");
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Route: GET /di/services, /di/resolve/{name} (lifetimes)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto list = f.client->get("/di/services");
|
||||
check(list.status == 200 && contains(list.body, "singleton") && contains(list.body, "transient") &&
|
||||
contains(list.body, "scoped"), "lists lifetimes");
|
||||
auto a = f.client->get("/di/resolve/config");
|
||||
auto b = f.client->get("/di/resolve/config");
|
||||
check(a.body == b.body, "singleton is stable");
|
||||
auto m1 = f.client->get("/di/resolve/mailer");
|
||||
auto m2 = f.client->get("/di/resolve/mailer");
|
||||
check(m1.body != m2.body, "transient differs");
|
||||
auto s1 = f.client->get("/di/resolve/request-context?scope=r1");
|
||||
auto s2 = f.client->get("/di/resolve/request-context?scope=r1");
|
||||
auto s3 = f.client->get("/di/resolve/request-context?scope=r2");
|
||||
check(s1.body == s2.body && s1.body != s3.body, "scoped per scope key");
|
||||
check(f.client->get("/di/resolve/ghost").status == 404, "unknown 404");
|
||||
check(contains(f.client->get("/di/services").body, "<td>2</td>"), "side effect: resolve counts");
|
||||
check(f.client->request(Method::Post, "/di/services").status == 405, "post is 405");
|
||||
return finish("di/services");
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// Route: GET /expose/stats, POST /expose/record (per-method table, windowed kB/s)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto empty = f.client->get("/expose/stats");
|
||||
check(empty.status == 200 && contains(empty.body, "_total"), "page with total row");
|
||||
auto form = f.client->get("/expose/record");
|
||||
check(form.status == 200 && contains(form.body, "<form"), "record form");
|
||||
const std::map<std::string, std::string> h = {{"Content-Type", "application/x-www-form-urlencoded"}};
|
||||
auto ok = f.client->request(Method::Post, "/expose/record", "method=GET&bytes_up=2048&bytes_down=10240µs=4000", h);
|
||||
check(ok.status == 303 && ok.headers.get("Location") == "/expose/stats", "redirect");
|
||||
f.client->request(Method::Post, "/expose/record", "method=GET&bytes_up=0&bytes_down=0µs=2000", h);
|
||||
auto js = f.client->request(Method::Get, "/expose/stats", "", {{"Accept", "application/json"}});
|
||||
check(contains(js.body, "\"GET\":{\"count\":2"), "count per method");
|
||||
check(contains(js.body, "\"kb_up\":2.0") && contains(js.body, "\"kb_down\":10.0"), "kB up and down");
|
||||
check(contains(js.body, "\"avg_ms\":3.00"), "average latency");
|
||||
check(contains(js.body, "\"kb_s_down\":0.17"), "windowed kB/s (10 kB over 60 s)");
|
||||
auto bad = f.client->request(Method::Post, "/expose/record", "method=FETCH&bytes_up=-1&bytes_down=xµs=", h);
|
||||
check(bad.status == 422 && contains(bad.body, "field-error"), "inline errors in page");
|
||||
auto badjson = f.client->request(Method::Post, "/expose/record", "method=FETCH&bytes_up=1&bytes_down=1µs=1",
|
||||
{{"Content-Type", "application/x-www-form-urlencoded"}, {"Accept", "application/json"}});
|
||||
check(badjson.status == 422 && contains(badjson.body, "method"), "json client gets json");
|
||||
check(f.client->request(Method::Delete, "/expose/stats").status == 405, "delete is 405");
|
||||
return finish("expose/stats");
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Route: GET /flash, POST /flash/set (cookie flash shown once)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(contains(f.client->get("/flash").body, "No flash message"), "empty at start");
|
||||
auto bad = f.client->request(Method::Post, "/flash/set", "message=", {{"Content-Type", "application/x-www-form-urlencoded"}});
|
||||
check(bad.status == 422 && contains(bad.body, "field-error"), "inline validation error");
|
||||
auto set = f.client->request(Method::Post, "/flash/set", "message=Saved+%3Cb%3E", {{"Content-Type", "application/x-www-form-urlencoded"}});
|
||||
check(set.status == 303 && set.headers.get("Location") == "/flash", "redirect");
|
||||
check(contains(set.headers.get("Set-Cookie"), "flash="), "flash cookie set");
|
||||
auto once = f.client->get("/flash");
|
||||
check(contains(once.body, "Saved <b>"), "shown escaped");
|
||||
check(contains(once.headers.get("Set-Cookie"), "Max-Age=0"), "cookie cleared");
|
||||
check(contains(f.client->get("/flash").body, "No flash message"), "gone on next view");
|
||||
auto too_long = f.client->request(Method::Post, "/flash/set", "message=" + std::string(300, 'a'), {{"Content-Type", "application/x-www-form-urlencoded"}});
|
||||
check(too_long.status == 422, "length limit");
|
||||
check(f.client->request(Method::Delete, "/flash").status == 405, "delete is 405");
|
||||
return finish("flash/flash");
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Route: GET/POST /governance/diff (breaking change detection)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/governance/diff").status == 200, "form");
|
||||
auto bad = f.client->post("/governance/diff", "before=GET+%2Fa", "application/x-www-form-urlencoded");
|
||||
check(bad.status == 422 && contains(bad.body, "field-error"), "after required");
|
||||
std::string before = "GET /items required=id\nDELETE /items required=id\n";
|
||||
std::string after = "GET /items required=id,page\nPOST /items required=name\n";
|
||||
auto r = f.client->request(Method::Post, "/governance/diff", "before=" + before + "&after=" + after, {{"Accept", "application/json"}});
|
||||
check(r.status == 200 && contains(r.body, "\"breaking\":2"), "two breaking changes");
|
||||
check(contains(r.body, "operation removed") && contains(r.body, "new required parameter page"), "details");
|
||||
check(contains(r.body, "operation added"), "compatible addition");
|
||||
auto same = f.client->request(Method::Post, "/governance/diff", "before=GET /a&after=GET /a", {{"Accept", "application/json"}});
|
||||
check(contains(same.body, "\"breaking\":0"), "side effect: identical specs clean");
|
||||
return finish("governance/diff");
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Route: GET/POST /governance/keys (+ revoke, whoami): API keys with scopes
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/governance/keys").status == 200, "form page");
|
||||
auto bad = f.client->post("/governance/keys", "owner=&tier=gold", "application/x-www-form-urlencoded");
|
||||
check(bad.status == 422 && contains(bad.body, "field-error"), "inline errors");
|
||||
auto js = f.client->request(Method::Post, "/governance/keys", "owner=ada&tier=free&scopes=read", {{"Accept", "application/json"}});
|
||||
check(js.status == 201 && contains(js.body, "mk_"), "issued");
|
||||
std::string key = js.body.substr(js.body.find("mk_"), 35);
|
||||
auto who = f.client->request(Method::Get, "/governance/whoami", "", {{"X-API-Key", key}});
|
||||
check(who.status == 200 && contains(who.body, "ada"), "authenticates");
|
||||
check(f.client->get("/governance/whoami").status == 401, "missing key 401");
|
||||
check(f.client->request(Method::Get, "/governance/whoami", "", {{"X-API-Key", "mk_bogus"}}).status == 401, "unknown 401");
|
||||
auto nos = f.client->request(Method::Post, "/governance/keys", "owner=bob&scopes=write", {{"Accept", "application/json"}});
|
||||
std::string k2 = nos.body.substr(nos.body.find("mk_"), 35);
|
||||
check(f.client->request(Method::Get, "/governance/whoami", "", {{"X-API-Key", k2}}).status == 403, "missing scope 403");
|
||||
check(f.client->post("/governance/keys/key1/revoke").status == 200, "revoke");
|
||||
auto rev = f.client->request(Method::Get, "/governance/whoami", "", {{"X-API-Key", key}});
|
||||
check(rev.status == 401 && contains(rev.body, "Revoked"), "side effect: revoked key rejected");
|
||||
check(f.client->post("/governance/keys/nope/revoke").status == 404, "unknown revoke 404");
|
||||
return finish("governance/keys");
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Route: GET/POST /governance/lint (route linter, HTML form)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/governance/lint").status == 200, "form");
|
||||
auto bad = f.client->post("/governance/lint", "paths=", "application/x-www-form-urlencoded");
|
||||
check(bad.status == 422 && contains(bad.body, "field-error") && !contains(bad.body, "\"failures\""), "inline error");
|
||||
auto ok = f.client->post("/governance/lint", "paths=%2Fusers%2F%0A%2FgetUser%0A%2Fuser_list%0A%2Fusers", "application/x-www-form-urlencoded");
|
||||
check(ok.status == 200 && contains(ok.body, "no-trailing-slash"), "trailing slash found");
|
||||
check(contains(ok.body, "lowercase-only") && contains(ok.body, "kebab-case"), "other rules");
|
||||
auto clean = f.client->request(Method::Post, "/governance/lint", "paths=/users\n/orders", {{"Accept", "application/json"}});
|
||||
check(contains(clean.body, "\"findings\":[]"), "clean paths: no findings (json)");
|
||||
auto verbs = f.client->request(Method::Post, "/governance/lint", "paths=/api/get/users", {{"Accept", "application/json"}});
|
||||
check(contains(verbs.body, "no-verbs-in-path"), "side effect: verb rule");
|
||||
return finish("governance/lint");
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Route: GET /governance/problem[/:status] (RFC 7807)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/governance/problem").status == 200, "overview");
|
||||
auto p = f.client->get("/governance/problem/404");
|
||||
check(p.status == 404 && contains(p.headers.get("Content-Type"), "application/problem+json"), "problem content type");
|
||||
check(contains(p.body, "\"status\":404") && contains(p.body, "\"title\"") && contains(p.body, "\"instance\""), "rfc7807 members");
|
||||
auto bad = f.client->get("/governance/problem/200");
|
||||
check(bad.status == 400 && contains(bad.headers.get("Content-Type"), "problem+json"), "out of range is 400");
|
||||
check(f.client->get("/governance/problem/abc").status == 400, "non numeric");
|
||||
check(f.client->post("/governance/problem/404").status == 405, "405");
|
||||
return finish("governance/problem");
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Route: GET /governance/tiers (+ whoami rate-limit headers)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto t = f.client->get("/governance/tiers");
|
||||
check(t.status == 200 && contains(t.body, "\"per_min\":3") && contains(t.body, "\"per_min\":10"), "tiers");
|
||||
auto js = f.client->request(Method::Post, "/governance/keys", "owner=ada&tier=free&scopes=read", {{"Accept", "application/json"}});
|
||||
std::string key = js.body.substr(js.body.find("mk_"), 35);
|
||||
auto r1 = f.client->request(Method::Get, "/governance/whoami", "", {{"X-API-Key", key}});
|
||||
check(r1.headers.get("X-RateLimit-Limit") == "3" && r1.headers.get("X-RateLimit-Remaining") == "2", "headers");
|
||||
check(r1.headers.get("X-Tier") == "free", "tier header");
|
||||
f.client->request(Method::Get, "/governance/whoami", "", {{"X-API-Key", key}});
|
||||
f.client->request(Method::Get, "/governance/whoami", "", {{"X-API-Key", key}});
|
||||
auto r4 = f.client->request(Method::Get, "/governance/whoami", "", {{"X-API-Key", key}});
|
||||
check(r4.status == 429 && r4.headers.get("Retry-After") == "60", "limit 429 with Retry-After");
|
||||
check(contains(r4.headers.get("Content-Type"), "problem+json"), "problem body");
|
||||
check(r4.headers.get("X-RateLimit-Remaining") == "0", "side effect: ledger exhausted");
|
||||
return finish("governance/tiers");
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Route: GET /governance/versions (version table)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto r = f.client->get("/governance/versions");
|
||||
check(r.status == 200 && contains(r.body, "\"deprecated\":true") && contains(r.body, "\"deprecated\":false"), "table");
|
||||
check(contains(r.body, "GMT"), "sunset date listed");
|
||||
check(f.client->post("/governance/versions").status == 405, "405");
|
||||
check(contains(r.headers.get("Content-Type"), "application/json"), "json");
|
||||
return finish("governance/versions");
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Route: GET /healthz /readyz /startupz (probes, startup gate, 503)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto live = f.client->get("/healthz");
|
||||
check(live.status == 200 && contains(live.body, "alive"), "liveness 200");
|
||||
check(contains(live.headers.get("Content-Type"), "application/json"), "json");
|
||||
check(f.client->get("/readyz").status == 200, "ready at start");
|
||||
check(f.client->get("/startupz").status == 200, "started");
|
||||
auto gate = f.client->request(Method::Post, "/startupz/tasks/seed-data?state=pending");
|
||||
check(gate.status == 503 && contains(gate.body, "pending"), "gate closed is 503");
|
||||
check(f.client->get("/readyz").status == 503, "not ready while starting");
|
||||
check(f.client->get("/healthz").status == 200, "liveness unaffected");
|
||||
f.client->request(Method::Post, "/startupz/tasks/seed-data?state=done");
|
||||
auto down = f.client->request(Method::Post, "/readyz/checks/database?state=down");
|
||||
check(down.status == 503 && contains(down.body, "\"database\":\"down\""), "failed check 503");
|
||||
check(f.client->request(Method::Post, "/readyz/checks/database?state=up").status == 200, "recovers");
|
||||
check(f.client->request(Method::Post, "/readyz/checks/database?state=meh").status == 422, "bad state 422");
|
||||
check(f.client->request(Method::Post, "/readyz/checks/nothing?state=up").status == 404, "unknown check 404");
|
||||
check(f.client->request(Method::Post, "/healthz").status == 405, "post is 405");
|
||||
return finish("healthz/probes");
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Route: GET /i18n (locale negotiation, plurals, .po dump)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto en = f.client->get("/i18n?n=1");
|
||||
check(en.status == 200, "status 200");
|
||||
check(contains(en.headers.get("Content-Type"), "text/html"), "html");
|
||||
check(contains(en.body, "1 item<"), "english singular");
|
||||
check(en.headers.get("Content-Language") == "en", "content-language en");
|
||||
auto ru = f.client->get("/i18n?lang=ru&n=22");
|
||||
check(contains(ru.body, "22 предмета"), "russian few form");
|
||||
auto ru5 = f.client->get("/i18n?lang=ru&n=5");
|
||||
check(contains(ru5.body, "5 предметов"), "russian many form");
|
||||
auto fr = f.client->get("/i18n?lang=fr&n=0");
|
||||
check(contains(fr.body, "0 article<"), "french zero is singular");
|
||||
auto hdr = f.client->request(Method::Get, "/i18n?n=2", "", {{"Accept-Language", "de;q=0.5, nl;q=0.9"}});
|
||||
check(hdr.headers.get("Content-Language") == "nl", "accept-language q weights");
|
||||
auto prm = f.client->request(Method::Get, "/i18n?lang=ja", "", {{"Accept-Language", "nl"}});
|
||||
check(prm.headers.get("Content-Language") == "ja", "?lang beats header");
|
||||
auto bad = f.client->get("/i18n?n=abc");
|
||||
check(bad.status == 422 && contains(bad.body, "field-error"), "inline validation error");
|
||||
check(!contains(bad.body, "{\""), "no raw json in page");
|
||||
auto huge = f.client->get("/i18n?n=99999999");
|
||||
check(huge.status == 422, "limit: count capped");
|
||||
auto po = f.client->get("/i18n/po?lang=ru");
|
||||
check(contains(po.body, "msgstr[2]") && contains(po.body, "nplurals=3"), "po catalog");
|
||||
check(f.client->get("/i18n/po?lang=xx").status == 404, "unknown locale 404");
|
||||
check(f.client->request(Method::Post, "/i18n").status == 405, "post is 405");
|
||||
return finish("i18n/page");
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Route: GET /logging/records, POST /logging/emit (levels, redaction, ring cap)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto form = f.client->get("/logging/emit");
|
||||
check(form.status == 200 && contains(form.body, "<form"), "form page");
|
||||
auto ok = f.client->request(Method::Post, "/logging/emit", "level=warn&message=login+password%3Dhunter2+failed",
|
||||
{{"Content-Type", "application/x-www-form-urlencoded"}, {"X-Correlation-ID", "abc-1"}});
|
||||
check(ok.status == 303 && ok.headers.get("Location") == "/logging/records", "redirect after emit");
|
||||
auto page = f.client->get("/logging/records");
|
||||
check(page.status == 200 && contains(page.body, "password=***"), "secret redacted");
|
||||
check(!contains(page.body, "hunter2"), "secret not shown");
|
||||
check(contains(page.body, "abc-1"), "correlation id kept");
|
||||
auto lines = f.client->get("/logging/records?format=json&level=warn");
|
||||
check(contains(lines.body, "\"level\":\"warn\"") && !contains(lines.body, "platform demo ready"), "json lines, level filter");
|
||||
auto bad = f.client->request(Method::Post, "/logging/emit", "level=loud&message=",
|
||||
{{"Content-Type", "application/x-www-form-urlencoded"}});
|
||||
check(bad.status == 422 && contains(bad.body, "field-error") && !contains(bad.body, "\"error\""), "html inline errors");
|
||||
auto js = f.client->request(Method::Post, "/logging/emit", "{\"level\":\"loud\"}",
|
||||
{{"Content-Type", "application/json"}});
|
||||
check(js.status == 422 && contains(js.body, "level"), "json client gets json");
|
||||
check(f.client->get("/logging/records?n=101").status == 422, "n capped at 100");
|
||||
for (int i = 0; i < 230; ++i)
|
||||
f.client->request(Method::Post, "/logging/emit", "level=info&message=m" + std::to_string(i),
|
||||
{{"Content-Type", "application/x-www-form-urlencoded"}});
|
||||
auto all = f.client->get("/logging/records?n=100&format=json");
|
||||
check(contains(all.body, "m229") && !contains(all.body, "m100\""), "newest first, capped to n");
|
||||
check(contains(f.client->get("/logging/records").body, "now 200"), "ring capped at 200");
|
||||
check(f.client->request(Method::Delete, "/logging/records").status == 405, "delete is 405");
|
||||
return finish("logging/records");
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Route: GET / (every matrix link resolves; no dead rows)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto index = f.client->get("/");
|
||||
check(index.status == 200, "index renders");
|
||||
std::size_t pos = 0, rows = 0;
|
||||
const std::string marker = "<td><a href=\"";
|
||||
while ((pos = index.body.find(marker, pos)) != std::string::npos) {
|
||||
pos += marker.size();
|
||||
std::string href = index.body.substr(pos, index.body.find('"', pos) - pos);
|
||||
// The template escapes '&' in hrefs.
|
||||
for (std::size_t a; (a = href.find("&")) != std::string::npos;)
|
||||
href.replace(a, 5, "&");
|
||||
auto res = f.client->get(href);
|
||||
// /auth/me demands credentials by design; every other row must be 2xx/3xx.
|
||||
bool ok = res.status < 400 || (href == "/auth/me" && res.status == 401);
|
||||
check(ok, "matrix link " + href + " -> " + std::to_string(res.status));
|
||||
++rows;
|
||||
}
|
||||
check(rows >= 37, "matrix lists at least the original 37 rows");
|
||||
return finish("matrix");
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Route: GET/POST /middleware/demo (builtin chain: headers, body limit, timing)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto res = f.client->get("/middleware/demo");
|
||||
check(res.status == 200, "status 200");
|
||||
check(res.headers.get("X-Content-Type-Options") == "nosniff", "secure headers");
|
||||
check(res.headers.get("X-Frame-Options") == "DENY", "frame options");
|
||||
check(res.headers.has("X-Response-Time-Us"), "timing header");
|
||||
auto small = f.client->request(Method::Post, "/middleware/demo", "tiny");
|
||||
check(small.status == 200 && contains(small.body, "Received 4 body bytes"), "small body passes");
|
||||
auto big = f.client->request(Method::Post, "/middleware/demo", std::string(65, 'x'));
|
||||
check(big.status == 413, "body limit 413");
|
||||
check(big.headers.get("X-Frame-Options") == "DENY", "outer middleware still runs on short circuit");
|
||||
check(f.client->request(Method::Delete, "/middleware/demo").status == 405, "delete is 405");
|
||||
return finish("middleware/demo");
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// Route: /operability/breaker (closed -> open -> half-open -> closed)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto page = f.client->get("/operability/breaker");
|
||||
check(page.status == 200, "status 200");
|
||||
check(contains(page.headers.get("Content-Type"), "text/html"), "html");
|
||||
check(contains(page.body, "closed"), "starts closed");
|
||||
for (int i = 0; i < 3; ++i) f.client->post("/operability/breaker/failure", "", kForm);
|
||||
check(contains(f.client->get("/operability/breaker").body, ">open<"), "three failures open it");
|
||||
auto rej = f.client->post("/operability/breaker/success", "", kForm);
|
||||
check(contains(rej.body, "rejected: breaker open"), "call rejected while open");
|
||||
for (int i = 0; i < 3; ++i) f.client->post("/operability/breaker/tick", "", kForm);
|
||||
check(contains(f.client->get("/operability/breaker").body, ">half-open<"), "30 s later half-open");
|
||||
f.client->post("/operability/breaker/success", "", kForm);
|
||||
check(contains(f.client->get("/operability/breaker").body, ">closed<"), "good probe closes");
|
||||
auto json = f.client->request(Method::Post, "/operability/breaker/failure", "", {{"Accept", "application/json"}});
|
||||
check(json.status == 200 && contains(json.body, "\"name\":\"breaker\""), "json client gets state");
|
||||
check(f.client->request(Method::Delete, "/operability/breaker").status == 405, "405 on delete");
|
||||
check(contains(f.client->get("/operability/debug").body, "\"breaker\""), "side effect: debug snapshot lists it");
|
||||
return finish("operability/breaker");
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Route: /operability/bulkhead (2 slots, queue of 1, then reject)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/operability/bulkhead").status == 200, "status 200");
|
||||
auto a = f.client->post("/operability/bulkhead/acquire", "", kForm);
|
||||
check(contains(a.body, ">admitted<") || contains(a.body, "admitted"), "first admitted");
|
||||
f.client->post("/operability/bulkhead/acquire", "", kForm);
|
||||
auto q = f.client->post("/operability/bulkhead/acquire", "", kForm);
|
||||
check(contains(q.body, "queued"), "third queued");
|
||||
auto r = f.client->post("/operability/bulkhead/acquire", "", kForm);
|
||||
check(contains(r.body, "rejected: compartment full"), "fourth rejected (limit)");
|
||||
check(contains(r.body, "2/2"), "side effect: active slots full");
|
||||
check(f.client->post("/operability/bulkhead/nope", "", kForm).status == 404, "404 unknown action");
|
||||
for (int i = 0; i < 3; ++i) f.client->post("/operability/bulkhead/release", "", kForm);
|
||||
check(contains(f.client->post("/operability/bulkhead/release", "", kForm).body, "nothing to release"), "empty release is reported");
|
||||
return finish("operability/bulkhead");
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Route: /operability/chaos (dry run default, hard blast radius)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/operability/chaos").status == 200, "status 200");
|
||||
auto dry = f.client->post("/operability/chaos/run", "percent=40&max_faults=3", kForm);
|
||||
check(contains(dry.body, "dry run: 0 injected, 3 planned"), "default is a dry run");
|
||||
auto armed = f.client->post("/operability/chaos/run", "percent=40&max_faults=2&armed=1", kForm);
|
||||
check(contains(armed.body, "armed: 2 injected, 2 planned"), "armed run capped at max_faults");
|
||||
auto big = f.client->post("/operability/chaos/run", "percent=90&max_faults=9", kForm);
|
||||
check(big.status == 422 && contains(big.body, "must be between 0 and 50"), "percent above cap rejected");
|
||||
check(contains(big.body, "must be between 1 and 5"), "faults above cap rejected");
|
||||
check(contains(f.client->get("/operability/chaos").body, "total_injected"), "side effect: totals tracked");
|
||||
check(contains(f.client->get("/operability/chaos").body, ">2<"), "only the armed run injected");
|
||||
return finish("operability/chaos");
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// Route: /operability/coord (lease, election, lock with fencing tokens)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/operability/coord").status == 200, "status 200");
|
||||
auto a = f.client->post("/operability/coord/acquire", "key=lock&owner=a", kForm);
|
||||
check(contains(a.body, "granted token 1"), "a gets token 1");
|
||||
auto b = f.client->post("/operability/coord/acquire", "key=lock&owner=b", kForm);
|
||||
check(contains(b.body, "denied, held by a"), "b denied while lease live");
|
||||
f.client->post("/operability/coord/tick", "", kForm);
|
||||
f.client->post("/operability/coord/tick", "", kForm);
|
||||
auto b2 = f.client->post("/operability/coord/acquire", "key=lock&owner=b", kForm);
|
||||
check(contains(b2.body, "granted token 2"), "b gets token 2 after expiry");
|
||||
check(contains(f.client->post("/operability/coord/write", "key=lock&token=2", kForm).body, "write accepted"), "fresh token writes");
|
||||
auto stale = f.client->post("/operability/coord/write", "key=lock&token=1", kForm);
|
||||
check(contains(stale.body, "stale fencing token"), "stale token fenced off");
|
||||
auto bad = f.client->post("/operability/coord/acquire", "key=db&owner=a", kForm);
|
||||
check(bad.status == 422, "422 unknown key");
|
||||
check(contains(f.client->post("/operability/coord/acquire", "key=leader&owner=n1", kForm).body, "granted"), "election via leader key");
|
||||
check(contains(f.client->get("/operability/coord").body, "held by b"), "side effect: holder shown");
|
||||
return finish("operability/coord");
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Route: /operability/deadline (budget shared across hops)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/operability/deadline").status == 200, "status 200");
|
||||
auto ok = f.client->post("/operability/deadline/run", "budget_ms=100&hops=3", kForm);
|
||||
check(contains(ok.body, "all hops finished in budget"), "fits in budget");
|
||||
auto late = f.client->post("/operability/deadline/run", "budget_ms=70&hops=5", kForm);
|
||||
check(contains(late.body, "deadline exceeded at hop 3"), "expires at hop 3");
|
||||
check(contains(late.body, "call skipped"), "side effect: log shows skipped hop");
|
||||
auto bad = f.client->post("/operability/deadline/run", "budget_ms=99999&hops=0", kForm);
|
||||
check(bad.status == 422 && contains(bad.body, "must be between 0 and 5000"), "422 limit on budget");
|
||||
auto json = f.client->request(Method::Post, "/operability/deadline/run", "{\"budget_ms\":\"abc\"}", {{"Content-Type", "application/json"}});
|
||||
check(json.status == 422 && contains(json.headers.get("Content-Type"), "json"), "json client gets json error");
|
||||
return finish("operability/deadline");
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Route: /operability/debug (snapshot of every lab)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
f.client->post("/operability/slo/bad", "", kForm);
|
||||
auto res = f.client->get("/operability/debug");
|
||||
check(res.status == 200, "status 200");
|
||||
check(contains(res.headers.get("Content-Type"), "application/json"), "json");
|
||||
check(contains(res.body, "\"labs\""), "labs object");
|
||||
for (const char* n : {"breaker", "bulkhead", "shedder", "deadline", "slo", "chaos", "deploy", "coord", "supplychain", "client-retry", "client-session", "migrations", "transaction", "query", "singleflight", "ttl"})
|
||||
check(contains(res.body, std::string("\"") + n + "\":{"), std::string("lab present: ") + n);
|
||||
check(contains(res.body, "bad event"), "side effect: earlier action visible in log");
|
||||
check(f.client->post("/operability/debug", "", kForm).status == 405, "405 on post");
|
||||
return finish("operability/debug");
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// Route: /operability/deploy (rolling, blue-green, rollback)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/operability/deploy").status == 200, "status 200");
|
||||
f.client->post("/operability/deploy/start", "strategy=rolling&version=v2", kForm);
|
||||
f.client->post("/operability/deploy/step", "", kForm);
|
||||
check(contains(f.client->get("/operability/deploy").body, "v2,v1,v1,v1"), "one instance replaced");
|
||||
auto again = f.client->post("/operability/deploy/start", "strategy=rolling", kForm);
|
||||
check(contains(again.body, "already in progress"), "second rollout refused");
|
||||
auto rb = f.client->post("/operability/deploy/rollback", "", kForm);
|
||||
check(contains(rb.body, "v1,v1,v1,v1") && contains(rb.body, "rolled back"), "rollback restores fleet");
|
||||
f.client->post("/operability/deploy/start", "strategy=bluegreen&version=v3", kForm);
|
||||
f.client->post("/operability/deploy/step", "", kForm);
|
||||
check(contains(f.client->get("/operability/deploy").body, "v1,v1,v1,v1"), "green prepared, blue serves");
|
||||
f.client->post("/operability/deploy/step", "", kForm);
|
||||
auto done = f.client->get("/operability/deploy");
|
||||
check(contains(done.body, "v3,v3,v3,v3") && contains(done.body, "done"), "switched");
|
||||
auto bad = f.client->post("/operability/deploy/start", "strategy=canary", kForm);
|
||||
check(bad.status == 422 && contains(bad.body, "must be one of: rolling, bluegreen"), "422 unknown strategy");
|
||||
return finish("operability/deploy");
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Route: /operability/shedder (low priority shed first)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/operability/shedder").status == 200, "status 200");
|
||||
f.client->post("/operability/shedder/enter", "priority=low", kForm);
|
||||
f.client->post("/operability/shedder/enter", "priority=low", kForm);
|
||||
auto low = f.client->post("/operability/shedder/enter", "priority=low", kForm);
|
||||
check(contains(low.body, "shed"), "third low request shed");
|
||||
auto high = f.client->post("/operability/shedder/enter", "priority=high", kForm);
|
||||
check(contains(high.body, "accepted"), "high priority still accepted");
|
||||
auto bad = f.client->post("/operability/shedder/enter", "priority=urgent", kForm);
|
||||
check(bad.status == 422 && contains(bad.body, "must be one of: low, high"), "422 inline error");
|
||||
check(!contains(bad.body, "{\"errors\""), "no raw json in page");
|
||||
check(contains(f.client->get("/operability/shedder").body, "3/3"), "side effect: inflight 3/3");
|
||||
return finish("operability/shedder");
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Route: /operability/slo (error budget burn)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/operability/slo").status == 200, "status 200");
|
||||
for (int i = 0; i < 20; ++i) f.client->post("/operability/slo/good", "", kForm);
|
||||
check(contains(f.client->get("/operability/slo").body, "healthy"), "healthy without bad events");
|
||||
f.client->post("/operability/slo/bad", "", kForm);
|
||||
check(contains(f.client->get("/operability/slo").body, "burning"), "one bad of 21 is within budget");
|
||||
f.client->post("/operability/slo/bad", "", kForm);
|
||||
f.client->post("/operability/slo/bad", "", kForm);
|
||||
check(contains(f.client->get("/operability/slo").body, "exhausted"), "budget exhausted");
|
||||
f.client->post("/operability/slo/reset", "", kForm);
|
||||
check(contains(f.client->get("/operability/slo").body, "0/100"), "side effect: window emptied");
|
||||
for (int i = 0; i < 105; ++i) f.client->request(Method::Post, "/operability/slo/good", "", {{"Accept", "application/json"}});
|
||||
check(contains(f.client->get("/operability/slo").body, "100/100"), "limit: window capped at 100");
|
||||
check(f.client->request(Method::Put, "/operability/slo").status == 405, "405 on put");
|
||||
return finish("operability/slo");
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Route: GET /metrics (Prometheus text: stats plus example metrics)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
f.services.metrics->inc("demo.hits", 3);
|
||||
f.client->get("/health");
|
||||
auto res = f.client->get("/metrics");
|
||||
check(res.status == 200, "status 200");
|
||||
check(contains(res.headers.get("Content-Type"), "text/plain; version=0.0.4"), "prometheus content type");
|
||||
check(contains(res.body, "# TYPE molo_http_requests_total counter"), "type line");
|
||||
check(contains(res.body, "molo_http_requests_total "), "request counter");
|
||||
check(contains(res.body, "molo_example_demo_hits 3"), "example metric sanitized");
|
||||
check(f.services.stats->total_requests() >= 2, "side effect: stats counted");
|
||||
check(f.client->request(Method::Post, "/metrics").status == 405, "post is 405");
|
||||
return finish("prom/metrics");
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Route: GET /security/admin (Bearer token, role permission check)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(contains(f.client->get("/security/roles").body, "admin:manage"), "roles page lists permissions");
|
||||
auto none = f.client->get("/security/admin");
|
||||
check(none.status == 401 && none.headers.get("WWW-Authenticate") == "Bearer", "no token 401");
|
||||
auto junk = f.client->request(Method::Get, "/security/admin", "", {{"Authorization", "Bearer nope"}});
|
||||
check(junk.status == 401, "unknown token 401");
|
||||
auto viewer = f.client->request(Method::Get, "/security/admin", "", {{"Authorization", "Bearer viewer-token"}});
|
||||
check(viewer.status == 403 && contains(viewer.body, "viewer"), "viewer 403");
|
||||
auto admin = f.client->request(Method::Get, "/security/admin", "", {{"Authorization", "Bearer admin-token"}});
|
||||
check(admin.status == 200 && contains(admin.body, "\"role\":\"admin\""), "admin 200");
|
||||
check(f.client->post("/security/admin", "x").status == 405, "POST 405");
|
||||
check(contains(f.client->get("/security/denials").body, "lacks admin:manage"), "side effect: denial recorded");
|
||||
return finish("security/admin");
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Route: OPTIONS /security/cors (origin allowlist preflight)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/security/cors").status == 200, "info page 200");
|
||||
auto ok = f.client->request(Method::Options, "/security/cors", "",
|
||||
{{"Origin", "https://app.example.com"}});
|
||||
check(ok.status == 204, "allowed origin is 204");
|
||||
check(ok.headers.get("Access-Control-Allow-Origin") == "https://app.example.com", "origin echoed");
|
||||
check(ok.headers.has("Access-Control-Allow-Methods"), "methods header");
|
||||
auto bad = f.client->request(Method::Options, "/security/cors", "", {{"Origin", "https://evil.example"}});
|
||||
check(bad.status == 403, "unknown origin is 403");
|
||||
check(!bad.headers.has("Access-Control-Allow-Origin"), "no allow header on denial");
|
||||
auto none = f.client->request(Method::Options, "/security/cors");
|
||||
check(none.status == 403, "missing origin is 403");
|
||||
auto post = f.client->post("/security/cors", "x");
|
||||
check(post.status == 405, "POST is 405");
|
||||
check(contains(f.client->get("/security/denials").body, "CorsPolicy"), "side effect: denial recorded");
|
||||
return finish("security/cors");
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// Route: /security/csrf (signed token, inline 403 on bad token)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto page = f.client->get("/security/csrf");
|
||||
check(page.status == 200 && contains(page.body, "<form"), "form renders");
|
||||
std::size_t at = page.body.find("value=\"");
|
||||
at = page.body.find("name=\"csrf_token\" value=\"");
|
||||
check(at != std::string::npos, "token field prefilled");
|
||||
at += std::string("name=\"csrf_token\" value=\"").size();
|
||||
std::string token = page.body.substr(at, page.body.find('"', at) - at);
|
||||
auto ok = f.client->post("/security/csrf", "csrf_token=" + token + "¬e=hi", kForm);
|
||||
check(ok.status == 200 && contains(ok.body, "Saved: hi"), "valid token accepted");
|
||||
auto missing = f.client->post("/security/csrf", "note=hi", kForm);
|
||||
check(missing.status == 403, "missing token is 403");
|
||||
check(contains(missing.body, "form-errors") && contains(missing.body, "invalid CSRF token"), "inline html error");
|
||||
check(!contains(missing.body, "\"error\""), "no raw json");
|
||||
auto bad = f.client->post("/security/csrf", "csrf_token=abc.def¬e=hi", kForm);
|
||||
check(bad.status == 403, "forged token is 403");
|
||||
auto longnote = f.client->post("/security/csrf", "csrf_token=" + token + "¬e=" + std::string(81, 'x'), kForm);
|
||||
check(longnote.status == 422, "note over 80 chars is 422");
|
||||
auto api = f.client->request(molo::example::fw::Method::Post, "/security/csrf", "note=hi",
|
||||
{{"Content-Type", kForm}, {"Accept", "application/json"}});
|
||||
check(api.status == 403 && contains(api.body, "CsrfGuard"), "json client gets json");
|
||||
auto denials = f.client->get("/security/denials");
|
||||
check(contains(denials.body, "CsrfGuard"), "side effect: denial recorded");
|
||||
return finish("security/csrf");
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Route: GET /security/denials (capped ring of refusals)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(contains(f.client->get("/security/denials").body, "\"total\":0"), "starts empty");
|
||||
for (int i = 0; i < 120; ++i) f.client->post("/security/guard", "kind=x&value=a", kForm);
|
||||
auto r = f.client->get("/security/denials");
|
||||
check(r.status == 200 && contains(r.body, "\"total\":120"), "total counts all");
|
||||
std::size_t n = 0, p = 0;
|
||||
while ((p = r.body.find("\"guard\"", p)) != std::string::npos) { ++n; p += 7; }
|
||||
check(n == 100, "ring capped at 100");
|
||||
check(f.client->post("/security/denials", "x").status == 405, "POST 405");
|
||||
return finish("security/denials");
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Route: /security/guard (SqlSafety and PathGuard rejection)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(contains(f.client->get("/security/guard").body, "<form"), "form renders");
|
||||
auto ok = f.client->post("/security/guard", "kind=sql&value=ada", kForm);
|
||||
check(ok.status == 200 && contains(ok.body, "safe for sql"), "safe sql value");
|
||||
auto sql = f.client->post("/security/guard", "kind=sql&value=x%27+OR+1%3D1+--", kForm);
|
||||
check(sql.status == 422 && contains(sql.body, "form-errors"), "sql injection inline 422");
|
||||
auto path = f.client->post("/security/guard", "kind=path&value=..%2F..%2Fetc%2Fpasswd", kForm);
|
||||
check(path.status == 422 && contains(path.body, "traversal"), "traversal rejected");
|
||||
auto abs = f.client->post("/security/guard", "kind=path&value=%2Fetc%2Fpasswd", kForm);
|
||||
check(abs.status == 422 && contains(abs.body, "absolute"), "absolute rejected");
|
||||
check(f.client->post("/security/guard", "kind=x&value=a", kForm).status == 422, "bad kind 422");
|
||||
check(f.client->post("/security/guard", "kind=sql&value=" + std::string(513, 'a'), kForm).status == 422, "over cap 422");
|
||||
check(contains(f.client->get("/security/denials").body, "PathGuard"), "side effect: denial recorded");
|
||||
return finish("security/guard");
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Route: GET /security/headers (hardening headers applied)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto r = f.client->get("/security/headers");
|
||||
check(r.status == 200, "status 200");
|
||||
check(r.headers.get("X-Content-Type-Options") == "nosniff", "nosniff");
|
||||
check(r.headers.get("X-Frame-Options") == "DENY", "frame deny");
|
||||
check(r.headers.has("Strict-Transport-Security"), "hsts");
|
||||
check(contains(r.body, "Referrer-Policy"), "body lists headers");
|
||||
check(f.client->post("/security/headers", "x").status == 405, "POST is 405");
|
||||
return finish("security/headers");
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Route: /security/login (HTML login form, session cookie)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(contains(f.client->get("/security/login").body, "type=\"password\""), "form renders");
|
||||
check(f.client->get("/security/whoami").status == 401, "anonymous whoami 401");
|
||||
auto bad = f.client->post("/security/login", "username=ada&password=nope", kForm);
|
||||
check(bad.status == 401 && contains(bad.body, "wrong username or password"), "bad creds inline 401");
|
||||
check(!contains(bad.body, "\"error\""), "no raw json");
|
||||
auto empty = f.client->post("/security/login", "username=&password=", kForm);
|
||||
check(empty.status == 422 && contains(empty.body, "form-errors"), "empty inline 422");
|
||||
auto ok = f.client->post("/security/login", "username=ada&password=correct-horse", kForm);
|
||||
check(ok.status == 200 && contains(ok.body, "Signed in as ada"), "login ok");
|
||||
check(contains(ok.headers.get("Set-Cookie"), "login_sid="), "session cookie set");
|
||||
auto who = f.client->get("/security/whoami");
|
||||
check(who.status == 200 && contains(who.body, "\"user\":\"ada\""), "whoami via cookie");
|
||||
check(f.services.sessions->size() >= 1, "side effect: session stored");
|
||||
return finish("security/login");
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Route: GET /security/rate (5 hits per 60 s per client, then 429)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
int main() {
|
||||
Fixture f;
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
auto r = f.client->request(Method::Get, "/security/rate", "", {{"X-Client-Id", "a"}});
|
||||
check(r.status == 200, "hit " + std::to_string(i + 1) + " allowed");
|
||||
if (i == 4) check(contains(r.body, "\"remaining\":0"), "remaining reaches 0");
|
||||
}
|
||||
auto limited = f.client->request(Method::Get, "/security/rate", "", {{"X-Client-Id", "a"}});
|
||||
check(limited.status == 429, "6th hit is 429");
|
||||
int retry = std::atoi(limited.headers.get("Retry-After").c_str());
|
||||
check(retry >= 1 && retry <= 61, "Retry-After within window");
|
||||
auto other = f.client->request(Method::Get, "/security/rate", "", {{"X-Client-Id", "b"}});
|
||||
check(other.status == 200, "other client unaffected");
|
||||
check(f.client->post("/security/rate", "x").status == 405, "POST is 405");
|
||||
check(contains(f.client->get("/security/denials").body, "RateLimiter"), "side effect: denial recorded");
|
||||
return finish("security/rate");
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Route: GET /security/secrets (values are always masked)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto list = f.client->get("/security/secrets");
|
||||
check(list.status == 200 && contains(list.body, "DB_PASSWORD"), "names listed");
|
||||
check(!contains(list.body, "demo-db-password"), "no values in list");
|
||||
auto one = f.client->get("/security/secrets?name=API_KEY");
|
||||
check(one.status == 200 && contains(one.body, "de*"), "masked value");
|
||||
check(!contains(one.body, "demo-api-key-abcdef"), "full value never returned");
|
||||
check(f.client->get("/security/secrets?name=NOPE").status == 404, "unknown 404");
|
||||
check(f.client->post("/security/secrets", "x").status == 405, "POST 405");
|
||||
return finish("security/secrets");
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Route: /security/upload (extension allowlist, size cap, magic bytes)
|
||||
#include "support/Assert.hpp"
|
||||
using namespace molo::example::test;
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(contains(f.client->get("/security/upload").body, "<form"), "form renders");
|
||||
auto ok = f.client->post("/security/upload", "filename=a.pdf&content_hex=255044462d31", kForm);
|
||||
check(ok.status == 200 && contains(ok.body, "Accepted a.pdf"), "valid pdf accepted");
|
||||
auto fake = f.client->post("/security/upload", "filename=a.png&content_hex=255044462d31", kForm);
|
||||
check(fake.status == 422 && contains(fake.body, "magic bytes"), "magic mismatch inline 422");
|
||||
auto ext = f.client->post("/security/upload", "filename=a.exe&content_hex=4d5a", kForm);
|
||||
check(ext.status == 422 && contains(ext.body, "extension not allowed"), "bad extension");
|
||||
auto path = f.client->post("/security/upload", "filename=..%2Fa.txt&content_hex=6869", kForm);
|
||||
check(path.status == 422, "path in name rejected");
|
||||
auto hex = f.client->post("/security/upload", "filename=a.txt&content_hex=zz", kForm);
|
||||
check(hex.status == 422 && contains(hex.body, "hex digits"), "bad hex");
|
||||
auto big = f.client->post("/security/upload", "filename=a.txt&content_hex=" + std::string(2050, '4') + std::string(2050, '1'), kForm);
|
||||
check(big.status == 422 || big.status == 413, "oversize rejected");
|
||||
auto bigok = f.client->post("/security/upload", "filename=a.txt&content_hex=" + std::string(2050, '6'), kForm);
|
||||
check(bigok.status == 413, "over 1024 bytes is 413");
|
||||
check(contains(f.client->get("/security/denials").body, "UploadValidator"), "side effect: denial recorded");
|
||||
return finish("security/upload");
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Route: /supplychain (SBOM, pins, advisories, attestation gate)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
static const char* kForm = "application/x-www-form-urlencoded";
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto page = f.client->get("/supplychain");
|
||||
check(page.status == 200 && contains(page.body, "chartjs"), "sbom listed");
|
||||
check(contains(page.body, ">PASS<"), "gate passes initially");
|
||||
auto sbom = f.client->get("/supplychain/sbom.json");
|
||||
check(sbom.status == 200 && contains(sbom.body, "CycloneDX"), "cyclonedx json");
|
||||
auto adv = f.client->post("/supplychain/advisory", "", kForm);
|
||||
check(contains(adv.body, ">FAIL<"), "advisory on a used version fails the gate");
|
||||
f.client->post("/supplychain/reset", "", kForm);
|
||||
check(contains(f.client->get("/supplychain").body, ">PASS<"), "reset restores the gate");
|
||||
f.client->post("/supplychain/tamper", "", kForm);
|
||||
check(contains(f.client->get("/supplychain").body, ">FAIL<"), "tampered component fails pins and attestation");
|
||||
auto bad = f.client->post("/supplychain/verify", "digest=abc", kForm);
|
||||
check(bad.status == 422 && contains(bad.body, "at least 16"), "422 short digest");
|
||||
auto wrong = f.client->post("/supplychain/verify", "digest=0000000000000000", kForm);
|
||||
check(contains(wrong.body, "attestation FAILED"), "wrong digest fails verification");
|
||||
check(contains(wrong.body, "failed"), "side effect: last_verify recorded");
|
||||
f.client->post("/supplychain/reset", "", kForm);
|
||||
auto defaults = f.client->get("/supplychain");
|
||||
check(contains(defaults.body, "value=\""), "verify form prefilled with the attested digest");
|
||||
return finish("supplychain/index");
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Route: GET/POST /tenancy/config (config overlay)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
Method P = Method::Post;
|
||||
check(contains(f.client->get("/tenancy/config").body, "\"theme\":\"light\""), "base value");
|
||||
check(f.client->request(P, "/tenancy/config", "key=theme&value=dark", {{"X-Tenant-ID", "acme"}}).status == 200, "set overlay");
|
||||
check(contains(f.client->request(Method::Get, "/tenancy/config", "", {{"X-Tenant-ID", "acme"}}).body, "\"theme\":\"dark\""), "overlay wins");
|
||||
check(contains(f.client->request(Method::Get, "/tenancy/config", "", {{"X-Tenant-ID", "globex"}}).body, "\"theme\":\"light\""), "side effect: other tenant keeps base");
|
||||
check(f.client->request(P, "/tenancy/config", "key=bogus&value=x", {{"X-Tenant-ID", "acme"}}).status == 422, "unknown key");
|
||||
check(f.client->request(P, "/tenancy/config", "key=theme&value=", {{"X-Tenant-ID", "acme"}}).status == 422, "empty value");
|
||||
return finish("tenancy/config");
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Route: GET/POST /tenancy/data (tenant-scoped data isolation, cap)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto add = f.client->request(Method::Post, "/tenancy/data", "item=alpha", {{"X-Tenant-ID", "acme"}});
|
||||
check(add.status == 201, "add");
|
||||
auto acme = f.client->request(Method::Get, "/tenancy/data", "", {{"X-Tenant-ID", "acme"}});
|
||||
check(contains(acme.body, "alpha"), "visible to owner");
|
||||
auto globex = f.client->request(Method::Get, "/tenancy/data", "", {{"X-Tenant-ID", "globex"}});
|
||||
check(!contains(globex.body, "alpha"), "side effect: isolated from other tenant");
|
||||
check(f.client->request(Method::Post, "/tenancy/data", "item=", {{"X-Tenant-ID", "acme"}}).status == 422, "empty item 422");
|
||||
int last = 0;
|
||||
for (int i = 0; i < 55; ++i)
|
||||
last = f.client->request(Method::Post, "/tenancy/data", "item=x", {{"X-Tenant-ID", "acme"}}).status;
|
||||
check(last == 429, "per-tenant cap 429");
|
||||
check(f.client->get("/tenancy/data").status == 200, "default tenant GET");
|
||||
return finish("tenancy/data");
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Route: GET/POST /tenancy/flags (per-tenant overrides)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
Method P = Method::Post;
|
||||
auto def = f.client->request(Method::Get, "/tenancy/flags", "", {{"X-Tenant-ID", "acme"}});
|
||||
check(def.status == 200 && contains(def.body, "\"beta-ui\":false"), "default off");
|
||||
check(f.client->request(P, "/tenancy/flags", "flag=beta-ui&enabled=true", {{"X-Tenant-ID", "acme"}}).status == 200, "set");
|
||||
check(contains(f.client->request(Method::Get, "/tenancy/flags", "", {{"X-Tenant-ID", "acme"}}).body, "\"beta-ui\":true"), "override applied");
|
||||
check(contains(f.client->request(Method::Get, "/tenancy/flags", "", {{"X-Tenant-ID", "globex"}}).body, "\"beta-ui\":false"), "side effect: other tenant unchanged");
|
||||
check(f.client->request(P, "/tenancy/flags", "flag=nope&enabled=true", {{"X-Tenant-ID", "acme"}}).status == 422, "unknown flag");
|
||||
check(f.client->request(P, "/tenancy/flags", "flag=beta-ui&enabled=maybe", {{"X-Tenant-ID", "acme"}}).status == 422, "bad value");
|
||||
return finish("tenancy/flags");
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Route: GET /tenancy/metrics (per-tenant counters)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
check(f.client->get("/tenancy/metrics").status == 200, "empty ok");
|
||||
f.client->request(Method::Get, "/tenancy/data", "", {{"X-Tenant-ID", "acme"}});
|
||||
f.client->request(Method::Get, "/tenancy/data", "", {{"X-Tenant-ID", "acme"}});
|
||||
f.client->request(Method::Get, "/tenancy/data", "", {{"X-Tenant-ID", "globex"}});
|
||||
auto m = f.client->get("/tenancy/metrics");
|
||||
check(contains(m.body, "\"acme\":{\"data.list\":2}"), "acme counted twice");
|
||||
check(contains(m.body, "\"globex\":{\"data.list\":1}"), "globex counted once");
|
||||
check(f.client->post("/tenancy/metrics").status == 405, "405 on post");
|
||||
return finish("tenancy/metrics");
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Route: GET/POST /tenancy/provision (HTML form, inline errors)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto page = f.client->get("/tenancy/provision");
|
||||
check(page.status == 200 && contains(page.headers.get("Content-Type"), "text/html"), "form page");
|
||||
auto bad = f.client->post("/tenancy/provision", "id=Bad&name=&plan=gold", "application/x-www-form-urlencoded");
|
||||
check(bad.status == 422 && contains(bad.headers.get("Content-Type"), "text/html"), "html 422");
|
||||
check(contains(bad.body, "field-error") && !contains(bad.body, "\"failures\""), "inline errors, no raw json");
|
||||
auto ok = f.client->post("/tenancy/provision", "id=initech&name=Initech&plan=pro", "application/x-www-form-urlencoded");
|
||||
check(ok.status == 201 && contains(ok.body, "provisioned"), "created");
|
||||
check(f.client->get("/tenancy/t/initech/whoami").status == 200, "side effect: tenant resolves");
|
||||
auto dup = f.client->post("/tenancy/provision", "id=initech&name=X&plan=free", "application/x-www-form-urlencoded");
|
||||
check(dup.status == 422 && contains(dup.body, "exists"), "duplicate rejected");
|
||||
auto js = f.client->request(Method::Post, "/tenancy/provision", "{\"id\":\"b\"}", {{"Content-Type", "application/json"}});
|
||||
check(js.status == 422 && contains(js.headers.get("Content-Type"), "application/json"), "json client gets json");
|
||||
return finish("tenancy/provision");
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Route: GET/POST /tenancy/quota (plan quotas)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
Method P = Method::Post;
|
||||
check(f.client->get("/tenancy/quota").status == 200, "get");
|
||||
int s = 0;
|
||||
for (int i = 0; i < 3; ++i) s = f.client->request(P, "/tenancy/quota", "", {{"X-Tenant-ID", "globex"}}).status;
|
||||
check(s == 200, "free plan allows 3");
|
||||
auto over = f.client->request(P, "/tenancy/quota", "", {{"X-Tenant-ID", "globex"}});
|
||||
check(over.status == 429 && over.headers.get("Retry-After") == "60", "4th is 429 with Retry-After");
|
||||
auto pro = f.client->request(P, "/tenancy/quota", "", {{"X-Tenant-ID", "acme"}});
|
||||
check(pro.status == 200 && contains(pro.body, "\"limit\":10"), "pro has bigger limit");
|
||||
check(contains(f.client->get("/tenancy/metrics").body, "quota.denied"), "side effect: denied metric");
|
||||
check(f.client->request(P, "/tenancy/quota", "", {{"X-Tenant-ID", "ghost"}}).status == 404, "unknown tenant");
|
||||
return finish("tenancy/quota");
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Route: GET /tenancy/resolve (tenant from header, subdomain, default)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto def = f.client->get("/tenancy/resolve");
|
||||
check(def.status == 200 && contains(def.body, "\"source\":\"default\""), "default tenant");
|
||||
check(contains(def.headers.get("Content-Type"), "application/json"), "json type");
|
||||
auto hdr = f.client->request(Method::Get, "/tenancy/resolve", "", {{"X-Tenant-ID", "acme"}});
|
||||
check(contains(hdr.body, "\"tenant\":\"acme\"") && contains(hdr.body, "header"), "header wins");
|
||||
auto sub = f.client->request(Method::Get, "/tenancy/resolve", "", {{"Host", "globex.example.com"}});
|
||||
check(contains(sub.body, "subdomain") && contains(sub.body, "globex"), "subdomain");
|
||||
auto bad = f.client->request(Method::Get, "/tenancy/resolve", "", {{"X-Tenant-ID", "Bad_ID"}});
|
||||
check(bad.status == 400 && contains(bad.headers.get("Content-Type"), "problem+json"), "malformed id is 400 problem");
|
||||
auto none = f.client->request(Method::Get, "/tenancy/resolve", "", {{"X-Tenant-ID", "nobody"}});
|
||||
check(none.status == 404, "unknown tenant 404");
|
||||
check(f.client->post("/tenancy/resolve").status == 405, "405 on post");
|
||||
auto m = f.client->get("/tenancy/metrics");
|
||||
check(contains(m.body, "\"resolve\""), "side effect: metric counted");
|
||||
return finish("tenancy/resolve");
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Route: GET /tenancy/t/{tenant}/whoami (path resolution)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto ok = f.client->get("/tenancy/t/acme/whoami");
|
||||
check(ok.status == 200 && contains(ok.body, "\"source\":\"path\"") && contains(ok.body, "pro"), "path tenant");
|
||||
check(f.client->get("/tenancy/t/x/whoami").status == 400, "too short id");
|
||||
check(f.client->get("/tenancy/t/ghost/whoami").status == 404, "unknown 404");
|
||||
auto h = f.client->request(Method::Get, "/tenancy/t/acme/whoami", "", {{"X-Tenant-ID", "globex"}});
|
||||
check(contains(h.body, "globex"), "header beats path");
|
||||
return finish("tenancy/t/tenant/whoami");
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Route: GET /v1/items (deprecated version: Deprecation, Sunset, Link)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto r = f.client->get("/v1/items");
|
||||
check(r.status == 200 && contains(r.body, "\"v1\""), "ok");
|
||||
check(r.headers.get("Deprecation") == "true", "Deprecation header");
|
||||
check(contains(r.headers.get("Sunset"), "GMT"), "Sunset header");
|
||||
check(contains(r.headers.get("Link"), "successor-version") && contains(r.headers.get("Link"), "/v2/items"), "Link successor");
|
||||
check(f.client->post("/v1/items").status == 405, "405 on post");
|
||||
check(f.client->get("/v1/nothing").status == 404, "404");
|
||||
return finish("v1/items");
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Route: GET /v2/items (current version: no deprecation headers)
|
||||
#include "support/Assert.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using molo::example::fw::Method;
|
||||
|
||||
int main() {
|
||||
Fixture f;
|
||||
auto r = f.client->get("/v2/items");
|
||||
check(r.status == 200 && contains(r.body, "\"v2\""), "ok");
|
||||
check(r.headers.get("X-API-Version") == "v2", "version header");
|
||||
check(!r.headers.has("Deprecation") && !r.headers.has("Sunset"), "no deprecation");
|
||||
check(f.client->post("/v2/items").status == 405, "405 on post");
|
||||
check(f.client->get("/v3/items").status == 404, "404 unknown version");
|
||||
return finish("v2/items");
|
||||
}
|
||||
Reference in New Issue
Block a user