mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Moved the PureBasic version to OldSource/, Started the Rust rewrite in Source/
The rewrite's plan and decisions are in revamp.md. Steps 0 to 10 are done: the workspace and checks, bakashrot-proto, bakashrot-pki and bakashrot-cert, bakashrot-config, bakashrot-storage (schema v9), the server and the client library (every request but replication's, attachments and retention included), the C DLL with its C, PureBasic and Python bindings, and the bakashrot tool. Step 11 (replication) is next. OldSource/ is the old implementation, kept building and passing as the reference. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
# The new sources (Source/): the same checks as Source/check.ps1, on Windows
|
||||
# and Linux. Gitea Actions runs this file too.
|
||||
name: Source
|
||||
|
||||
on:
|
||||
push:
|
||||
paths: ["Source/**", ".github/workflows/source.yml"]
|
||||
pull_request:
|
||||
paths: ["Source/**", ".github/workflows/source.yml"]
|
||||
|
||||
jobs:
|
||||
check:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-latest, ubuntu-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
defaults:
|
||||
run:
|
||||
working-directory: Source
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
# Installs the toolchain Source/rust-toolchain.toml pins.
|
||||
- run: rustup toolchain install
|
||||
- run: cargo fmt --all -- --check
|
||||
- run: cargo clippy --workspace --all-targets --all-features -- -D warnings
|
||||
- run: cargo test --workspace --all-features
|
||||
- run: cargo doc --workspace --no-deps --all-features
|
||||
env:
|
||||
RUSTDOCFLAGS: -D warnings
|
||||
+7
-4
@@ -5,8 +5,8 @@
|
||||
# Build Artifacts
|
||||
*.exe
|
||||
*.dll
|
||||
# ... except the runtime redistributables the release packages, see Libs/redist/README.md
|
||||
!Libs/redist/**/*.dll
|
||||
# ... except the runtime redistributables the old release packages, see OldSource/Libs/redist/README.md
|
||||
!OldSource/Libs/redist/**/*.dll
|
||||
*.so
|
||||
*.a
|
||||
*.pdb
|
||||
@@ -22,7 +22,10 @@ Release/
|
||||
# Python
|
||||
__pycache__/
|
||||
|
||||
# Rust (Source/)
|
||||
target/
|
||||
|
||||
# The examples run their server in their own folder: its database, and
|
||||
# what their client scripts write
|
||||
Examples/**/*.sqlite*
|
||||
Examples/**/out/
|
||||
OldSource/Examples/**/*.sqlite*
|
||||
OldSource/Examples/**/out/
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
[submodule "Includes/PB-MessagePack"]
|
||||
path = Includes/PB-MessagePack
|
||||
path = OldSource/Includes/PB-MessagePack
|
||||
url = https://github.com/aziascreations/PB-MessagePack.git
|
||||
|
||||
@@ -1,116 +1,46 @@
|
||||
# BakaShrot - start here
|
||||
|
||||
A message store with replication, in PureBasic: servers take JSON (or any)
|
||||
messages per topic/node from authenticated clients, store them in SQLite,
|
||||
and replicate them between peers by name. Clients: a DLL, CLI tools, a
|
||||
Python module. An **internal tool on trusted machines**: correctness and
|
||||
operations come before security hardening (`Notes.md`, "Threat model").
|
||||
A message store with replication: servers take messages per topic/node
|
||||
from authenticated clients, store them in SQLite, and replicate them
|
||||
between peers by name. Clients: a C DLL, CLI tools, a Python module. An
|
||||
**internal tool on trusted machines**.
|
||||
|
||||
## Read first
|
||||
**Being rewritten in Rust** (since 2026-11-13):
|
||||
|
||||
1. `Notes.md`: "Right now" (what's committed, what's next), where things
|
||||
stand, "Open items, by importance" (the to-do list), "Testing tips".
|
||||
2. `Design/`, by topic: `Packets.md` (the protocol, where every file lives,
|
||||
code conventions), `Attachments.md`, `Cryptography.md`,
|
||||
`StorageConcurrency.md`, `ReplicationIssues.md`, `Release.md`,
|
||||
`Suggestions.md`.
|
||||
3. `git log --oneline` and `git status`: what's committed. Work happens on
|
||||
branches off `master` (`timestamps-retention` at this writing).
|
||||
- `revamp.md`: why, what's decided, what's proposed and open, the plan and
|
||||
its status. Read it first.
|
||||
- `Source/`: the new implementation (`Source/README.md`: layout, commands,
|
||||
conventions; `Source/docs/`: designs, `protocol.md` first).
|
||||
- `OldSource/`: the old PureBasic implementation, the reference for the
|
||||
behaviour to carry over. It has its own `CLAUDE.md` (build, test, traps),
|
||||
`Notes.md` and `Design/`; its paths are relative to `OldSource/`.
|
||||
|
||||
## Build
|
||||
## Toolchain
|
||||
|
||||
- Dev compiler, PureBasic 5.73: `C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe <src> /EXE <out> [flags]`.
|
||||
Release compiler, 6.40 C backend: `C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe <src> /OUTPUT <out> /OPTIMIZER`.
|
||||
Code must compile with both (`Release.ps1` checks the 6.40 side).
|
||||
- `Build.ps1` builds everything into `Build\`, **regenerates keys and
|
||||
configs, then runs a server waiting on its console**: don't run it from
|
||||
an automated shell. To rebuild after a change, compile what changed:
|
||||
|
||||
| Source | Output | Flags |
|
||||
|---|---|---|
|
||||
| `Server\BakaShrot_Server.pb` | `Build\BakaShrot_Server.exe` | `/CONSOLE /THREAD` |
|
||||
| `Client\BakaShrot_Client.pbi` | `Build\BakaShrot_Client.dll` | `/DLL /THREAD` |
|
||||
| `Tools\<Name>\<Name>.pb` (BakaShrot + PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query, ResolveIds, List, GenerateKeyPairs) | `Build\<Name>.exe` | `/CONSOLE` |
|
||||
| `Client\BakaShrot_Client_Prototypes.pbi` | `Build\ClientExample.exe` | `/CONSOLE` |
|
||||
| `Tests\Bench\BenchServer.pb` (the server with a stop file, used by every test) | `Build\Bench\BenchServer.exe` | `/CONSOLE /THREAD` |
|
||||
| `Tests\Bench\BenchClient.pb`, `BenchSeed.pb` | `Build\Bench\` | `/CONSOLE /THREAD` |
|
||||
| `Tests\HandshakeTest.pb`, `Tests\CipherTest.pb` | `Build\` | `/CONSOLE` |
|
||||
| `Tests\AttachmentEdgeClient.pb` | `Build\AttachmentEdgeClient.exe` | `/CONSOLE /THREAD` |
|
||||
|
||||
- `Release.ps1 [-Force]` builds the release with 6.40 into `Release\` and
|
||||
smoke-tests it (`-Force` replaces an existing folder of the same name).
|
||||
- Linux: same sources and flags (`-t`, `-e`, `-so` for the DLL), with
|
||||
`libsodium-dev`. `Docker/Server/` builds the server image, on the
|
||||
PureBasic image `git.nibblepoker.lu/packages/purebasic` (6.41, linux3;
|
||||
needs a `docker login`), see its Dockerfile.
|
||||
|
||||
## Test
|
||||
|
||||
Each suite starts its own servers (`BenchServer.exe`) on fixed ports, in a
|
||||
fresh folder under `Build\`, and prints PASS/FAIL lines; exit code 0 means
|
||||
all passed. `powershell -ExecutionPolicy Bypass -File Tests\<Suite>.ps1`:
|
||||
|
||||
| Suite | Ports | Covers |
|
||||
|---|---|---|
|
||||
| `Names-Test.ps1` | 12401-12402 | names/ids, filters, wildcards, replication by name |
|
||||
| `BigMessages-Test.ps1` | 12403-12404 | 16 MB messages, handshake frame limit, `is_json`, query errors |
|
||||
| `GetMessages-Test.ps1` | 12405 | runs of messages, `--follow` |
|
||||
| `Python-Test.ps1` | 12406-12407 | `bakashrot.py` (`check_bakashrot.py`), the wire is encrypted (`wire_check.py`) |
|
||||
| `Retention-Test.ps1` | 12408-12409 | `pushed_at`, retention, schema upgrade (Python) |
|
||||
| `Attachments-Test.ps1` | 12410-12411 | attachments through the tools, replication, limits |
|
||||
| `AttachmentEdges-Test.ps1` | 12413-12414 | raw-protocol edge cases, expiry, resuming, corruption (Python) |
|
||||
| `Restart-Test.ps1` | 12415-12416 | servers killed mid-traffic and mid-catch-up: nothing acknowledged lost, ids carry on, both catch up (Python pushers) |
|
||||
|
||||
Plus `Build\HandshakeTest.exe` and `Build\CipherTest.exe` (no server), and
|
||||
the release's smoke test. Speed: `Tests\Bench\Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp`
|
||||
(push ceiling for 4 servers: ~17,000 msg/s with the default `Synchronous =
|
||||
FULL`, ~34,000-40,000 with `-Synchronous NORMAL`). After a change, run every
|
||||
suite: they take a few minutes in all.
|
||||
|
||||
## Traps
|
||||
|
||||
- **Run exes from `Build\`**: the antivirus blocks them in temp folders.
|
||||
- **`Build\` holds private keys**: git-ignored, never publish it. The one
|
||||
exception: `Examples/*/` commit their configs, keys included, on purpose
|
||||
(public, example-only, marked so); don't copy those keys anywhere else.
|
||||
- **PureBasic is single pass**: constants, structures and procedures must
|
||||
be declared before use, so include order matters (e.g. `Config.pbi`
|
||||
includes `Packets.pbi` for its constants).
|
||||
- **`SetDatabase*()` binds the next statement run on that connection**, not
|
||||
a specific one: set them right before their `DatabaseUpdate/Query`.
|
||||
- **Never `Goto` out of a `Select`**: 5.73's ASM backend keeps the value on
|
||||
the stack, the jump corrupts it (a config error crashed the server with
|
||||
0xC0000005). Set the error, leave the `Select`, then jump. Out of
|
||||
`For`/`ForEach`/`While` loops is fine (checked on both compilers).
|
||||
- **PureBasic lists aren't safe to walk from several threads** (`ForEach`
|
||||
moves the shared current element): give each thread its own copy.
|
||||
- **Files mix CRLF and LF**: edits must keep each file's line endings.
|
||||
- **PowerShell 5**: JSON passed as an argument loses its double quotes
|
||||
(tests write it to a file, `@file`), and `@()` can't be passed through
|
||||
`-File`.
|
||||
- **Bash tool heredocs collapse `\\`**, and PureBasic uses `\` for fields:
|
||||
write edit scripts to files, or use the Edit tool.
|
||||
- **The real server needs a console on Windows** (it stops at once without
|
||||
input): tests use `BenchServer.exe` and its stop file instead. On Linux
|
||||
it runs on without one, SIGTERM/SIGINT stop it.
|
||||
- Rust via rustup, in `%USERPROFILE%\.cargo\bin`, which **isn't on every
|
||||
shell's PATH**: prepend it (`export PATH="$HOME/.cargo/bin:$PATH"` in
|
||||
bash; `check.ps1` does it itself). The toolchain is pinned
|
||||
(`Source/rust-toolchain.toml`, 1.100.0, MSVC; Visual Studio 18 has the
|
||||
linker).
|
||||
- `Source\check.ps1` runs what CI runs; it must pass before a step is done.
|
||||
- PureBasic 5.73 and 6.40 for `OldSource/`, see `OldSource/CLAUDE.md`.
|
||||
|
||||
## Working rules
|
||||
|
||||
- **Commit only when the owner asks**, on a branch, not `master`.
|
||||
- **Wire changes bump `#BakaShrot_ProtocolVersion`** (`Packets.pbi`, 6 at
|
||||
this writing); any difference refuses the connection.
|
||||
- **Schema changes** add a `Server/Storage/db_schema_vN.dbml` (v8 at this
|
||||
writing) and a migration in `SetupStorageDatabase()` (`Storage.pbi`),
|
||||
existing databases must keep working.
|
||||
- **Packets** follow `Design/Packets.md` "Code conventions": one file per
|
||||
packet in `Commons/Networking/Packets/`, `_Encode` / `_Decode` (and
|
||||
`_Free` when it holds data), every field validated on decode.
|
||||
- **Every write goes through the writer** (`Server/Storage/Writer.pbi`,
|
||||
under its mutex); reads use the thread's own connection.
|
||||
- **Every `.pb`/`.pbi` starts with a code header** (`;{- Code Header`,
|
||||
like PB-MessagePack's): name, version (0.0.1 at this writing), tested
|
||||
compilers. A release bumps the version in all of them; only list a
|
||||
compiler/platform once every suite passed with it.
|
||||
- **Docs follow the code**: a finished piece gets a "Done: ... (date)"
|
||||
section in `Notes.md`, what's left goes to its open items, and the
|
||||
`Design/` doc of that area is updated with it.
|
||||
- **Commit only when the owner asks**, on a branch (`revamp`), not `master`.
|
||||
- **Follow the plan's order** (`revamp.md`, "Plan"); a step is done when its
|
||||
tests pass and its docs are updated, then its status goes in the table.
|
||||
- **`OldSource/` is the reference:** don't change it beyond keeping it
|
||||
building and passing, unless asked.
|
||||
- **Decisions go in `revamp.md`**: moved to "Decided" only when the owner
|
||||
decides, with the date.
|
||||
- **Use existing crates** rather than reimplementing (MessagePack is `rmp-serde`).
|
||||
- **Files mix CRLF and LF:** edits must keep each file's line endings
|
||||
(`Source/` is LF, the docs at the root and in `OldSource/` mostly CRLF).
|
||||
- **Bash tool heredocs collapse `\\`:** write edit scripts to files, or use
|
||||
the Edit tool.
|
||||
- **Run exes from a build folder** (`OldSource\Build\`, `Source\target\`):
|
||||
the antivirus blocks them in temp folders.
|
||||
- **Generated keys and certificates never go in git** (`Build/`,
|
||||
`target/`). The one exception: `OldSource/Examples/*/` commit theirs on
|
||||
purpose (public, example-only, marked so).
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# BakaShrot, the old PureBasic implementation - start here
|
||||
|
||||
**Frozen since 2026-11-13** as the reference for the Rust rewrite
|
||||
(`../revamp.md`, `../CLAUDE.md`). Every path below is relative to this
|
||||
folder, `OldSource/`: run the scripts and compilers from here.
|
||||
|
||||
A message store with replication, in PureBasic: servers take JSON (or any)
|
||||
messages per topic/node from authenticated clients, store them in SQLite,
|
||||
and replicate them between peers by name. Clients: a DLL, CLI tools, a
|
||||
Python module. An **internal tool on trusted machines**: correctness and
|
||||
operations come before security hardening (`Notes.md`, "Threat model").
|
||||
|
||||
## Read first
|
||||
|
||||
1. `Notes.md`: "Right now" (what's committed, what's next), where things
|
||||
stand, "Open items, by importance" (the to-do list), "Testing tips".
|
||||
2. `Design/`, by topic: `Packets.md` (the protocol, where every file lives,
|
||||
code conventions), `Attachments.md`, `Cryptography.md`,
|
||||
`Certificates.md`, `StorageConcurrency.md`, `ReplicationIssues.md`,
|
||||
`Release.md`, `Suggestions.md`.
|
||||
3. `git log --oneline` and `git status`: what's committed. Work happens on
|
||||
branches off `master` (`timestamps-retention` at this writing).
|
||||
|
||||
## Build
|
||||
|
||||
- Dev compiler, PureBasic 5.73: `C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe <src> /EXE <out> [flags]`.
|
||||
Release compiler, 6.40 C backend: `C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe <src> /OUTPUT <out> /OPTIMIZER`.
|
||||
Code must compile with both (`Release.ps1` checks the 6.40 side).
|
||||
- `Build.ps1` builds everything into `Build\`, **regenerates keys and
|
||||
configs, then runs a server waiting on its console**: don't run it from
|
||||
an automated shell. To rebuild after a change, compile what changed:
|
||||
|
||||
| Source | Output | Flags |
|
||||
|---|---|---|
|
||||
| `Server\BakaShrot_Server.pb` | `Build\BakaShrot_Server.exe` | `/CONSOLE /THREAD` |
|
||||
| `Client\BakaShrot_Client.pbi` | `Build\BakaShrot_Client.dll` | `/DLL /THREAD` |
|
||||
| `Tools\<Name>\<Name>.pb` (BakaShrot + PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query, ResolveIds, List, GenerateKeyPairs) | `Build\<Name>.exe` | `/CONSOLE` |
|
||||
| `Client\BakaShrot_Client_Prototypes.pbi` | `Build\ClientExample.exe` | `/CONSOLE` |
|
||||
| `Tests\Bench\BenchServer.pb` (the server with a stop file, used by every test) | `Build\Bench\BenchServer.exe` | `/CONSOLE /THREAD` |
|
||||
| `Tests\Bench\BenchClient.pb`, `BenchSeed.pb` | `Build\Bench\` | `/CONSOLE /THREAD` |
|
||||
| `Tests\HandshakeTest.pb`, `Tests\CipherTest.pb`, `Tests\X509Test.pb` | `Build\` | `/CONSOLE` |
|
||||
| `Tests\AttachmentEdgeClient.pb` | `Build\AttachmentEdgeClient.exe` | `/CONSOLE /THREAD` |
|
||||
|
||||
- `Release.ps1 [-Force]` builds the release with 6.40 into `Release\` and
|
||||
smoke-tests it (`-Force` replaces an existing folder of the same name).
|
||||
- Linux: same sources and flags (`-t`, `-e`, `-so` for the DLL), with
|
||||
`libsodium-dev`. `Docker/Server/` builds the server image, on the
|
||||
PureBasic image `git.nibblepoker.lu/packages/purebasic` (6.41, linux3;
|
||||
needs a `docker login`), see its Dockerfile.
|
||||
|
||||
## Test
|
||||
|
||||
Each suite starts its own servers (`BenchServer.exe`) on fixed ports, in a
|
||||
fresh folder under `Build\`, and prints PASS/FAIL lines; exit code 0 means
|
||||
all passed. `powershell -ExecutionPolicy Bypass -File Tests\<Suite>.ps1`:
|
||||
|
||||
| Suite | Ports | Covers |
|
||||
|---|---|---|
|
||||
| `Names-Test.ps1` | 12401-12402 | names/ids, filters, wildcards, replication by name |
|
||||
| `BigMessages-Test.ps1` | 12403-12404 | 16 MB messages, handshake frame limit, `is_json`, query errors |
|
||||
| `GetMessages-Test.ps1` | 12405 | runs of messages, `--follow` |
|
||||
| `Python-Test.ps1` | 12406-12407 | `bakashrot.py` (`check_bakashrot.py`), the wire is encrypted (`wire_check.py`) |
|
||||
| `Retention-Test.ps1` | 12408-12409 | `pushed_at`, retention, schema upgrade (Python) |
|
||||
| `Attachments-Test.ps1` | 12410-12411 | attachments through the tools, replication, limits |
|
||||
| `AttachmentEdges-Test.ps1` | 12413-12414 | raw-protocol edge cases, expiry, resuming, corruption (Python) |
|
||||
| `Restart-Test.ps1` | 12415-12416 | servers killed mid-traffic and mid-catch-up: nothing acknowledged lost, ids carry on, both catch up (Python pushers) |
|
||||
| `X509-Test.ps1` | none | X.509 certificates (`X509Test.exe`), both ways with OpenSSL when it's there (Git's) |
|
||||
|
||||
Plus `Build\HandshakeTest.exe` and `Build\CipherTest.exe` (no server), and
|
||||
the release's smoke test. Speed: `Tests\Bench\Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp`
|
||||
(push ceiling for 4 servers: ~17,000 msg/s with the default `Synchronous =
|
||||
FULL`, ~34,000-40,000 with `-Synchronous NORMAL`). After a change, run every
|
||||
suite: they take a few minutes in all.
|
||||
|
||||
## Traps
|
||||
|
||||
- **Run exes from `Build\`**: the antivirus blocks them in temp folders.
|
||||
- **`Build\` holds private keys**: git-ignored, never publish it. The one
|
||||
exception: `Examples/*/` commit their configs, keys included, on purpose
|
||||
(public, example-only, marked so); don't copy those keys anywhere else.
|
||||
- **PureBasic is single pass**: constants, structures and procedures must
|
||||
be declared before use, so include order matters (e.g. `Config.pbi`
|
||||
includes `Packets.pbi` for its constants).
|
||||
- **`SetDatabase*()` binds the next statement run on that connection**, not
|
||||
a specific one: set them right before their `DatabaseUpdate/Query`.
|
||||
- **Never `Goto` out of a `Select`**: 5.73's ASM backend keeps the value on
|
||||
the stack, the jump corrupts it (a config error crashed the server with
|
||||
0xC0000005). Set the error, leave the `Select`, then jump. Out of
|
||||
`For`/`ForEach`/`While` loops is fine (checked on both compilers).
|
||||
- **PureBasic lists aren't safe to walk from several threads** (`ForEach`
|
||||
moves the shared current element): give each thread its own copy.
|
||||
- **Files mix CRLF and LF**: edits must keep each file's line endings.
|
||||
- **PowerShell 5**: JSON passed as an argument loses its double quotes
|
||||
(tests write it to a file, `@file`), and `@()` can't be passed through
|
||||
`-File`.
|
||||
- **Bash tool heredocs collapse `\\`**, and PureBasic uses `\` for fields:
|
||||
write edit scripts to files, or use the Edit tool.
|
||||
- **The real server needs a console on Windows** (it stops at once without
|
||||
input): tests use `BenchServer.exe` and its stop file instead. On Linux
|
||||
it runs on without one, SIGTERM/SIGINT stop it.
|
||||
|
||||
## Working rules
|
||||
|
||||
- **Commit only when the owner asks**, on a branch, not `master`.
|
||||
- **Wire changes bump `#BakaShrot_ProtocolVersion`** (`Packets.pbi`, 6 at
|
||||
this writing); any difference refuses the connection.
|
||||
- **Schema changes** add a `Server/Storage/db_schema_vN.dbml` (v8 at this
|
||||
writing) and a migration in `SetupStorageDatabase()` (`Storage.pbi`),
|
||||
existing databases must keep working.
|
||||
- **Packets** follow `Design/Packets.md` "Code conventions": one file per
|
||||
packet in `Commons/Networking/Packets/`, `_Encode` / `_Decode` (and
|
||||
`_Free` when it holds data), every field validated on decode.
|
||||
- **Every write goes through the writer** (`Server/Storage/Writer.pbi`,
|
||||
under its mutex); reads use the thread's own connection.
|
||||
- **Every `.pb`/`.pbi` starts with a code header** (`;{- Code Header`,
|
||||
like PB-MessagePack's): name, version (0.0.1 at this writing), tested
|
||||
compilers. A release bumps the version in all of them; only list a
|
||||
compiler/platform once every suite passed with it.
|
||||
- **Docs follow the code**: a finished piece gets a "Done: ... (date)"
|
||||
section in `Notes.md`, what's left goes to its open items, and the
|
||||
`Design/` doc of that area is updated with it.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -160,8 +160,38 @@ CompilerEndIf
|
||||
crypto_hash_sha256_update.l(*State, *Data, DataLength.q)
|
||||
crypto_hash_sha256_final.l(*State, *Hash)
|
||||
|
||||
; SHA-256 of DataLength bytes at *Data in one go, the 32-byte hash into
|
||||
; *Hash. Certificates' fingerprints and key ids (X509.pbi).
|
||||
crypto_hash_sha256.l(*Hash, *Data, DataLength.q)
|
||||
|
||||
; Fills *Buffer with Size bytes from the OS's secure generator.
|
||||
; Certificates' serial numbers.
|
||||
randombytes_buf(*Buffer, Size.i)
|
||||
|
||||
; The Ed25519 key pair of a 32-byte seed, which is what PKCS#8 private
|
||||
; key files hold, and the seed of a 64-byte private key. Both return 0.
|
||||
crypto_sign_seed_keypair.l(*PublicKey, *PrivateKey, *Seed)
|
||||
crypto_sign_ed25519_sk_to_seed.l(*Seed, *PrivateKey)
|
||||
|
||||
; Base64 (Variant #BakaShrot_Base64_Original for PEM), constant-time.
|
||||
; _encoded_len() is the size *Base64 needs, terminator included.
|
||||
; bin2base64 writes a terminated ASCII string, returns *Base64.
|
||||
; base642bin skips the characters of the ASCII string *Ignore (" \r\n"),
|
||||
; and returns -1 if anything else isn't Base64 or *Binary is too small
|
||||
; (*End = 0: all of it must decode). The size it wrote goes in *BinaryLength.
|
||||
sodium_base64_encoded_len.i(BinaryLength.i, Variant.l)
|
||||
sodium_bin2base64.i(*Base64, MaxLength.i, *Binary, BinaryLength.i, Variant.l)
|
||||
sodium_base642bin.l(*Binary, MaxLength.i, *Base64, Base64Length.i, *Ignore, *BinaryLength, *End, Variant.l)
|
||||
|
||||
; Hex, lowercase, constant-time; same conventions as Base64 above.
|
||||
sodium_bin2hex.i(*Hex, MaxLength.i, *Binary, BinaryLength.i)
|
||||
sodium_hex2bin.l(*Binary, MaxLength.i, *Hex, HexLength.i, *Ignore, *BinaryLength, *End)
|
||||
|
||||
EndImport
|
||||
|
||||
; sodium_base64_VARIANT_ORIGINAL: the standard alphabet, with padding.
|
||||
#BakaShrot_Base64_Original = 1
|
||||
|
||||
|
||||
; Must be called once at startup, before GenerateKeyPair/EncodeData/DecodeData.
|
||||
; Returns #False if libsodium could not initialize - treat that as fatal,
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,154 @@
|
||||
# Certificates - X.509 with Ed25519
|
||||
|
||||
Status (2026-11-13): an include in `Commons/Cryptography/`, tested on its
|
||||
own and against OpenSSL, **not used by anything yet**. Next: a tool that
|
||||
generates certificates, then the server and the client loading and
|
||||
checking them (see the end).
|
||||
|
||||
## Why it's written here
|
||||
|
||||
- **libsodium has no X.509 or ASN.1**, so the DER and the certificate
|
||||
structure are PureBasic (`Der.pbi`, `X509.pbi`). Every bit of
|
||||
cryptography is still libsodium's: Ed25519 signatures, SHA-256 (key ids,
|
||||
fingerprints), random serials, Base64 (PEM) and hex, seeds to key pairs
|
||||
(PKCS#8).
|
||||
- **Not the OS's APIs:** Windows' CryptoAPI can't check Ed25519
|
||||
certificates, and the identity keys are Ed25519 already. Not OpenSSL
|
||||
either: another library to ship and load on both OSes, for what's a few
|
||||
hundred lines of DER. One code for Windows and Linux.
|
||||
- **Standard certificates all the same:** OpenSSL reads them, verifies
|
||||
chains of them, reads the private keys, and they read and check OpenSSL's
|
||||
(`Tests/X509-Test.ps1`).
|
||||
|
||||
## Files
|
||||
|
||||
| File | What |
|
||||
|---|---|
|
||||
| `Commons/Cryptography/Der.pbi` | ASN.1 DER: a reader (strict) and a writer, integers, OIDs (any arc size), times, strings, bit strings. |
|
||||
| `Commons/Cryptography/X509.pbi` | Certificates: reading, issuing, checking, PEM, PKCS#8 private keys. Includes `Der.pbi` and `Libsodium.pbi`. |
|
||||
| `Tests/X509Test.pb` | 131 checks on its own, 145 with OpenSSL's certificates. |
|
||||
| `Tests/X509-Test.ps1` | Runs it, makes OpenSSL's certificates for it, checks its own with OpenSSL. |
|
||||
|
||||
## Reading
|
||||
|
||||
- `BakaShrot_X509_Parse(*Der, Size)`, `_ParsePem(Text)`, `_Load(Path)`
|
||||
(PEM or DER, by its first byte) give a `BakaShrot_X509Certificate`, freed
|
||||
with `BakaShrot_X509_Free()`. Failures give 0 and a code.
|
||||
- **Any certificate is read** (RSA, ECDSA...): version, serial, names,
|
||||
validity, algorithms, every extension. Only Ed25519 ones have their key
|
||||
and signature (`HasEd25519Key`, `HasEd25519Signature`), and only they can
|
||||
be checked or issue others (`Unsupported` otherwise).
|
||||
- **Strict DER:** shortest lengths and integers, no indefinite lengths, real
|
||||
dates, no NUL in strings, the inner and outer signature algorithms the same
|
||||
bytes, an extension once at most, v1 never written as such, nothing after
|
||||
the certificate. A reader never reads past its buffer. Every truncation of
|
||||
a certificate is refused, and of its 503 one-bit flips, the 335 that still
|
||||
parse all fail the checks.
|
||||
- **Known extensions** fill fields: BasicConstraints (`IsCa`,
|
||||
`PathLength`), KeyUsage (`KeyUsage`, `#BakaShrot_X509_KeyUsage_*` flags),
|
||||
the key ids (`SubjectKeyId`, `AuthorityKeyId`, hex). The others stay as
|
||||
they are (`Extensions()`: OID, critical, DER value).
|
||||
- Names keep their attributes in order (`Subject\Attributes()`): OID, text,
|
||||
string type, RDN index. `BakaShrot_X509_NameGet(@\Subject, "CN")`,
|
||||
`_NameToString()` ("CN=kitchen, OU=clients").
|
||||
|
||||
## Issuing
|
||||
|
||||
`BakaShrot_X509_Issue(*Template, *Issuer, *IssuerPrivateKey, *OutSize)`,
|
||||
the issuer 0 for a self-signed one. The template: subject, validity, the
|
||||
subject's public key, CA or not and its path length, key usage, the custom
|
||||
extensions. It writes:
|
||||
|
||||
- v3, a random positive 16-byte serial (or the template's), Ed25519.
|
||||
- The issuer's subject as the issuer certificate encodes it (so names match
|
||||
byte for byte).
|
||||
- Names one attribute per RDN: `C` as a PrintableString (2 letters),
|
||||
`emailAddress` and `DC` as IA5String, the rest UTF8String.
|
||||
- UTCTime from 1950 to 2049, GeneralizedTime otherwise (RFC 5280).
|
||||
- BasicConstraints (critical, always), KeyUsage (critical, if any), the
|
||||
subject's key id (the first 20 bytes of the key's SHA-256, RFC 7093) and
|
||||
the issuer's, then the template's extensions in order.
|
||||
|
||||
It refuses: a private key that isn't the issuer's (or the subject's when
|
||||
self-signed), an issuer that isn't a CA or lacks keyCertSign, a path length
|
||||
on a leaf, NotAfter before NotBefore, a name it can't write.
|
||||
|
||||
## Checking
|
||||
|
||||
Each returns `#BakaShrot_X509_Ok` (0) or what's wrong
|
||||
(`BakaShrot_X509_ErrorName()`): BadSignature, NotYetValid, Expired,
|
||||
IssuerMismatch, NotCa, PathTooLong, UnknownCritical, Unsupported...
|
||||
|
||||
- `BakaShrot_X509_CheckIssuedBy(*Cert, *Issuer, Now, Handled)`: one link.
|
||||
The issuer names match (as encoded), the key ids too when both have one,
|
||||
the issuer may issue, the signature is its key's, `*Cert` is valid at
|
||||
`Now` (both ends included), no critical extension is left unhandled.
|
||||
- `BakaShrot_X509_VerifyChain(Chain(), *Root, Now, Handled)`: the leaf
|
||||
first, then each issuer up to the one the trusted `*Root` issued. Every
|
||||
link as above, the root valid and a CA, the path lengths kept.
|
||||
- `_CheckSignature()`, `_CheckValidity()`, `_CanIssue()`,
|
||||
`_CheckCriticalExtensions()` on their own.
|
||||
- `Now` is seconds since 1970 UTC: `BakaShrot_X509_Now()`.
|
||||
- `Handled` lists the critical extensions the caller understands
|
||||
(`"oid;oid"`). RFC 5280: a critical extension a reader doesn't know makes
|
||||
the certificate unusable.
|
||||
|
||||
## Custom extensions
|
||||
|
||||
- **BakaShrot's OID arc:** `#BakaShrot_Oid_Arc`,
|
||||
`2.25.232025699926348910519219903487382490981`, a UUID OID (ITU-T X.667),
|
||||
which needs no registration (made from a random UUID, 2026-11-13). It
|
||||
could be swapped for a registered enterprise number (`1.3.6.1.4.1.<PEN>`)
|
||||
as long as no certificate was issued for real with it.
|
||||
- **Extensions:** `#BakaShrot_Oid_Extensions` (the arc + `.1`) + `.<n>`,
|
||||
numbered as they're defined, a number never reused. None is defined yet;
|
||||
the tests use 9000 and up.
|
||||
- **Writing:** `BakaShrot_X509_AddTextExtension(@Template, Oid, Text)`
|
||||
(UTF8String), `_AddIntegerExtension()`, `_AddExtension()` (any one DER
|
||||
element, a `BakaShrot_DerWriter` makes them), critical or not.
|
||||
- **Reading:** `BakaShrot_X509_GetExtensionText()`,
|
||||
`_GetExtensionInteger()`, or `_FindExtension()` and the raw value.
|
||||
- **Critical or not:** critical means "refuse me if you don't know me". For
|
||||
fields only BakaShrot reads, non-critical is the usual choice; critical
|
||||
if a reader that ignores it would grant too much (then pass it in
|
||||
`Handled`).
|
||||
- OpenSSL writes them too (`<oid> = ASN1:UTF8String:...` in an extensions
|
||||
file, as the test does), and shows them by OID.
|
||||
|
||||
## Private keys and PEM
|
||||
|
||||
- `BakaShrot_X509_PrivateKeyToPem()` / `_PrivateKeyFromPem()`: PKCS#8
|
||||
(RFC 8410), what `openssl genpkey -algorithm ed25519` writes, not
|
||||
encrypted. Reading takes v1 and v2 (with the public key, which must
|
||||
match). The seed and the DER are wiped after use.
|
||||
- `BakaShrot_Pem_Encode()` / `_Decode()` for any label, LF line endings;
|
||||
CRLF, spaces and text around the block are fine on reading.
|
||||
|
||||
## Threads
|
||||
|
||||
No globals. A parsed certificate is only read once made, and its names and
|
||||
extensions are arrays, not lists (`ForEach` moves a list's current element,
|
||||
see `CLAUDE.md`): any number of threads may check against the same CA.
|
||||
|
||||
## Not done
|
||||
|
||||
- **Using it:** a tool generating a CA, server and client certificates and
|
||||
keys; the server and client loading them, checking the other end's. How
|
||||
they'd fit the handshake (what replaces or joins the `PublicKeys` lists,
|
||||
the ClientHello carrying a certificate, the 4 KB handshake frame limit) is
|
||||
to decide with the client auth rework: a protocol change either way.
|
||||
- **Revocation:** no CRL or OCSP. Short validities, or a list of revoked
|
||||
serials or fingerprints in the configs, if it's ever needed.
|
||||
- **Not interpreted:** SubjectAltName, ExtendedKeyUsage, NameConstraints,
|
||||
policies. They're read as raw extensions; marked critical (NameConstraints
|
||||
usually is), they make a certificate refused unless in `Handled`.
|
||||
- **Names are matched as encoded**, byte for byte, not with RFC 5280's
|
||||
case-insensitive comparison. Fine for certificates issued here, which
|
||||
copy the issuer's encoding; another CA's could differ in string types.
|
||||
- Multi-valued RDNs are read, not written (one attribute per RDN).
|
||||
Encrypted PKCS#8, certificate requests (CSR): not done.
|
||||
- `BakaShrot_X509_Now()` repeats `BakaShrot_NowUtcMs()`
|
||||
(`Server/Storage/Storage.pbi`) in seconds, so `Commons/` doesn't depend on
|
||||
the server: one could move to `Commons/` for both.
|
||||
- Tested on Windows (5.73, 6.40 C) only so far; the Linux side
|
||||
(`gettimeofday`, `-lsodium`) is the same code as elsewhere but unrun.
|
||||
@@ -44,6 +44,11 @@ keys sit in plain-text ini files (see the end).
|
||||
| `crypto_aead_xchacha20poly1305_ietf_encrypt` / `_decrypt` | `BakaShrot_Cipher_Encrypt()`, `_EncryptTo()` / `_Decrypt()` | Every packet after the ChallengeRequest. |
|
||||
| `crypto_aead_xchacha20poly1305_ietf_keygen` | `BakaShrot_Cipher_GenerateKey()` | Tests only, real keys come from the handshake. |
|
||||
| `sodium_memzero` | `BakaShrot_Cipher_Clear()`, the `_Clear*()` of `Session.pbi` | Wipes keys. |
|
||||
| `crypto_hash_sha256` | `BakaShrot_X509_KeyId()`, `_Fingerprint()` | Certificates' key ids and fingerprints (`Design/Certificates.md`). |
|
||||
| `randombytes_buf` | `BakaShrot_X509_Issue()` | Random serial numbers. |
|
||||
| `crypto_sign_seed_keypair` / `crypto_sign_ed25519_sk_to_seed` | `BakaShrot_X509_PrivateKeyFromPem()` / `_PrivateKeyToPem()` | PKCS#8 files hold the 32-byte seed. |
|
||||
| `sodium_bin2base64` / `_base642bin` / `_base64_encoded_len` | `BakaShrot_Pem_Encode()` / `_Decode()` | PEM; line breaks skipped. |
|
||||
| `sodium_bin2hex` / `_hex2bin` | `BakaShrot_X509_Hex()` / `_FromHex()` | Serials, key ids. |
|
||||
|
||||
- **Base64 helpers**, in `Libsodium.pbi`:
|
||||
- `EncodeKeyToString()` encodes a key or signature.
|
||||
@@ -59,7 +59,7 @@ WINDOWS = {
|
||||
"tag": "py3-none-win_amd64",
|
||||
"libraries": ["BakaShrot_Client.dll", "libsodium.dll"],
|
||||
# In the wheel's dist-info/licenses/, from the repository's root.
|
||||
"licenses": {"LICENSE": "LICENSE", "libsodium/LICENSE": "Libs/libsodium/LICENSE"},
|
||||
"licenses": {"LICENSE": "../LICENSE", "libsodium/LICENSE": "Libs/libsodium/LICENSE"},
|
||||
"license_expression": "CC0-1.0 AND ISC",
|
||||
"classifier": "Operating System :: Microsoft :: Windows :: Windows 10",
|
||||
"summary": "Python client for BakaShrot servers, with the client DLL included",
|
||||
@@ -83,7 +83,7 @@ Denis's, under the ISC license: its notice is in this package's
|
||||
LINUX = {
|
||||
"tag": "py3-none-linux_x86_64",
|
||||
"libraries": ["BakaShrot_Client.dll"],
|
||||
"licenses": {"LICENSE": "LICENSE"},
|
||||
"licenses": {"LICENSE": "../LICENSE"},
|
||||
"license_expression": "CC0-1.0",
|
||||
"classifier": "Operating System :: POSIX :: Linux",
|
||||
"summary": "Python client for BakaShrot servers, with the client library included",
|
||||
@@ -9,11 +9,18 @@ Where things stand and what's next, as of 2026-11-09. A new session: read
|
||||
| `Design/Packets.md` | The protocol: framing, every packet, flows, conventions, how to add a packet. |
|
||||
| `Design/Attachments.md` | Attachments: one per message, in 1 MB parts, uploaded before the message, replicated after it. |
|
||||
| `Design/Cryptography.md` | What libsodium is used for: the handshake proving both ends, the connections' encryption. What isn't done, and ideas for abstracting it. |
|
||||
| `Design/Certificates.md` | X.509 certificates with Ed25519: reading, issuing, checking, custom extensions. Not used yet. |
|
||||
| `Design/ReplicationIssues.md` | Known replication problems, with benchmarks. |
|
||||
| `Design/StorageConcurrency.md` | One connection per thread, WAL, the write mutex and the writer (done), and what's left. |
|
||||
| `Design/Suggestions.md` | Improvements not done yet: pipelined pushes, faster replication, smaller ones. |
|
||||
| `Design/Release.md` | The release smoke test, what's missing for 1.0.0, the (fixed) silent query failure, notes for CI/CD. |
|
||||
|
||||
## Moved (2026-11-13)
|
||||
|
||||
- **This implementation is frozen** in `OldSource/` (branch `revamp`), the
|
||||
reference for the Rust rewrite: `../revamp.md`. Paths in these notes are
|
||||
relative to `OldSource/`. It still builds and passes from here.
|
||||
|
||||
## Right now (2026-11-10)
|
||||
|
||||
- **Everything is committed**, on `timestamps-retention`: protocol 6 and
|
||||
@@ -742,6 +749,33 @@ with every tool (all compile with `--optimizer`). Scripts not committed.
|
||||
`Interactors/Python/README.md`.
|
||||
- **Windows only.** Linux: open item 20, without bundling libsodium.
|
||||
|
||||
## Done: X.509 certificates, an include (2026-11-13, uncommitted)
|
||||
|
||||
- **`Commons/Cryptography/Der.pbi` and `X509.pbi`**, for the client auth
|
||||
rework: certificates the tools will generate, the server and the client
|
||||
load and check, with custom fields. Not used by anything yet.
|
||||
`Design/Certificates.md` has all of it.
|
||||
- **Written here, on libsodium:** libsodium has no X.509 or ASN.1, so the
|
||||
DER (strict) and the certificate structure are PureBasic; signatures,
|
||||
SHA-256, serials, Base64 and hex are libsodium's (new imports in
|
||||
`Libsodium.pbi`). Windows' CryptoAPI can't check Ed25519 certificates,
|
||||
OpenSSL would be another library to ship.
|
||||
- **Reads any certificate** (PEM or DER), checks and issues Ed25519 ones:
|
||||
one link or a chain up to a trusted root, validity, CA and key usage,
|
||||
path lengths, key ids, critical extensions. PKCS#8 private keys, PEM.
|
||||
- **Custom extensions** under BakaShrot's own OID arc, a UUID OID
|
||||
(`#BakaShrot_Oid_Arc`, `2.25.2320...0981`, no registration needed),
|
||||
`.1.<n>` for extensions; none defined yet.
|
||||
- **Tested:** `Tests/X509Test.pb` (131 checks alone, 145 with OpenSSL's
|
||||
certificates) and `Tests/X509-Test.ps1` (OpenSSL both ways: it verifies
|
||||
our leaf and chain, reads our key and custom extensions, matches our
|
||||
fingerprint; we read and check its Ed25519 CA and leaf, read its RSA
|
||||
one, issue with its CA). PB 5.73 and 6.40 C, Windows; `CipherTest` and
|
||||
the DLL still build and pass with the new imports. Linux not run.
|
||||
- **Left:** the generating tool, loading in the server and client, how it
|
||||
fits the handshake (protocol change); no revocation; see
|
||||
`Design/Certificates.md`, "Not done".
|
||||
|
||||
## Threat model (2026-11-08)
|
||||
|
||||
BakaShrot is an **internal tool, on trusted machines and a trusted
|
||||
@@ -150,7 +150,7 @@ Get-ChildItem $OutDir -Include "*.lib", "*.exp" -Recurse | Remove-Item -Force
|
||||
|
||||
Copy-Item $Sodium $OutDir
|
||||
Copy-Item $SodiumLicense (Join-Path $OutDir "LICENSE-libsodium.txt")
|
||||
Copy-Item (Join-Path $Root "LICENSE") (Join-Path $OutDir "LICENSE.txt")
|
||||
Copy-Item (Join-Path $Root "..\LICENSE") (Join-Path $OutDir "LICENSE.txt")
|
||||
foreach ($File in $Redist) { Copy-Item $File.FullName $OutDir }
|
||||
Copy-Item $SqliteDll (Join-Path $OutDir "sqlite3.dll")
|
||||
Copy-Item (Join-Path $Root "Client\BakaShrot_Client_Prototypes.pbi") $OutDir
|
||||
@@ -40,6 +40,18 @@
|
||||
; Compile as a thread-safe console program.
|
||||
; ============================================================================
|
||||
|
||||
|
||||
; ------------------------------------------------------------------------------
|
||||
;- Compiler directive
|
||||
|
||||
CompilerIf Not #PB_Compiler_IsMainFile
|
||||
CompilerError "The server's main file was included !"
|
||||
CompilerEndIf
|
||||
|
||||
CompilerIf Not #PB_Compiler_Thread
|
||||
CompilerError "The server must be compiled in thread-safe mode !"
|
||||
CompilerEndIf
|
||||
|
||||
EnableExplicit
|
||||
|
||||
XIncludeFile "Root.pbi"
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user