1
0
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:
2026-11-14 12:47:40 +01:00
parent d0048b17c8
commit e044fcf359
225 changed files with 21849 additions and 123 deletions
+389
View File
@@ -0,0 +1,389 @@
;{- Code Header
; ==- Basic Info -================================
; Name: AttachmentEdgeClient.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; A raw protocol client for the attachment cases the DLL never produces, run
; by Tests/AttachmentEdges-Test.ps1 against a running server.
;
; Usage:
; AttachmentEdgeClient edge <KitchenIni> <GarageIni>
; Wrong SHA-256, parts out of order / of the wrong size / repeated,
; someone else's upload, the wrong topic, an upload attached twice, too
; big, a part out of range. Then starts two uploads it leaves behind
; (one half sent, one complete but never pushed) and prints
; "LEFT <PartialId> <CompleteId>".
; AttachmentEdgeClient late <KitchenIni> <PartialId> <CompleteId>
; Once they expired: both refused.
; The inis are client.ini's: PrivateKey, PublicKey, ServerPublicKey, Topic,
; Node, ServerHost, ServerPort. Kitchen may push to logs and other, garage
; to logs; the server's MaxAttachmentSize must be under 1G.
; Compile as a thread-safe console program into Build\. Exits with 0 if
; every check passed, 1 otherwise.
; ============================================================================
EnableExplicit
XIncludeFile "../Commons/Networking/Outbound.pbi"
Structure EdgeClient
Outbound.BakaShrot_Outbound
Identity.BakaShrot_OutboundIdentity
PrivateKey.a[#BakaShrot_Ed25519_PrivateKeySize]
ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
EndStructure
Global Fails.i = 0
Procedure Check(What.s, Ok.i, Detail.s = "")
If Ok
PrintN("PASS " + What)
Else
PrintN("FAIL " + What)
Fails + 1
EndIf
PrintN(" -> " + Detail)
EndProcedure
Procedure.i ConnectIni(*Client.EdgeClient, IniPath.s)
Protected Host.s, Port.i, Ok.i
If Not OpenPreferences(IniPath)
ProcedureReturn #False
EndIf
PreferenceGroup("BakaShrot")
Ok = DecodeKeyFromString(ReadPreferenceString("PrivateKey", ""), @*Client\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize)
Ok = Bool(Ok And DecodeKeyFromString(ReadPreferenceString("ServerPublicKey", ""), @*Client\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize))
*Client\Identity\PublicKey = ReadPreferenceString("PublicKey", "")
*Client\Identity\Node = ReadPreferenceString("Node", "")
*Client\Identity\PrivateKey = @*Client\PrivateKey[0]
Host = ReadPreferenceString("ServerHost", "127.0.0.1")
Port = ReadPreferenceLong("ServerPort", 0)
ClosePreferences()
If Not Ok
ProcedureReturn #False
EndIf
ProcedureReturn BakaShrot_Outbound_Connect(@*Client\Outbound, Host, Port, @*Client\Identity, @*Client\ServerPublicKey[0])
EndProcedure
; Sends *Packet (freed), returns the answer with its type, 0 if the link failed.
Procedure.i Exchange(*Client.EdgeClient, *Packet, Size.i, *Type.Integer, *AnswerSize.Integer)
Protected *Answer
*Type\i = 0
If Not *Packet
ProcedureReturn 0
EndIf
If Not BakaShrot_Outbound_Send(@*Client\Outbound, *Packet, Size)
FreeMemory(*Packet)
ProcedureReturn 0
EndIf
FreeMemory(*Packet)
*Answer = BakaShrot_Outbound_WaitPacket(@*Client\Outbound, *AnswerSize, 20000)
If *Answer
*Type\i = BakaShrot_GetPacketType(*Answer, *AnswerSize\i)
EndIf
ProcedureReturn *Answer
EndProcedure
Procedure.s Refusal(*Answer, Size.i)
Protected *View.MsgPackData, *Refused.BakaShrot_RequestRefused, Reason.s
*View = MsgPackWrapMsgBuffer(*Answer, Size)
If *View
*Refused = BakaShrot_RequestRefusedPacket_Decode(*View)
MsgPackFree(*View, #False)
If *Refused
Reason = *Refused\Reason
FreeStructure(*Refused)
EndIf
EndIf
ProcedureReturn Reason
EndProcedure
; Starts an upload. Returns its id, 0 if refused (reason in *Reason\s).
Procedure.q StartUpload(*Client.EdgeClient, Topic.s, Size.q, *Sha256, *Reason.String)
Protected Start.BakaShrot_UploadStart, *Started.BakaShrot_UploadStarted
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Id.q
*Reason\s = ""
Start\Topic = Topic
Start\Size = Size
CopyMemory(*Sha256, @Start\Sha256[0], #BakaShrot_Sha256Size)
*Packet = BakaShrot_UploadStartPacket_Encode(@Start, @PacketSize)
*Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize)
If Not *Answer
*Reason\s = "the link failed"
ProcedureReturn 0
EndIf
If Type\i = #BakaShrot_PacketType_RequestRefused
*Reason\s = Refusal(*Answer, AnswerSize\i)
ElseIf Type\i = #BakaShrot_PacketType_UploadStarted
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
*Started = BakaShrot_UploadStartedPacket_Decode(*View)
MsgPackFree(*View, #False)
If *Started
Id = *Started\UploadId
FreeStructure(*Started)
EndIf
EndIf
FreeMemory(*Answer)
ProcedureReturn Id
EndProcedure
; Sends a part. Returns 1 if stored (*Complete\i set), 0 if refused (reason), -1 if the link failed.
Procedure.i SendChunk(*Client.EdgeClient, UploadId.q, Index.i, *Data, Size.i, *Complete.Integer, *Reason.String)
Protected Chunk.BakaShrot_UploadChunk, *Stored.BakaShrot_ChunkStored
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Result.i = -1
*Reason\s = ""
Chunk\UploadId = UploadId
Chunk\ChunkIndex = Index
Chunk\Data = *Data
Chunk\DataSize = Size
*Packet = BakaShrot_UploadChunkPacket_Encode(@Chunk, @PacketSize)
*Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize)
If Not *Answer
ProcedureReturn -1
EndIf
If Type\i = #BakaShrot_PacketType_RequestRefused
*Reason\s = Refusal(*Answer, AnswerSize\i)
Result = 0
ElseIf Type\i = #BakaShrot_PacketType_ChunkStored
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
*Stored = BakaShrot_ChunkStoredPacket_Decode(*View)
MsgPackFree(*View, #False)
If *Stored
*Complete\i = *Stored\Complete
FreeStructure(*Stored)
Result = 1
EndIf
EndIf
FreeMemory(*Answer)
ProcedureReturn Result
EndProcedure
; Pushes a message with UploadId. Returns its id, 0 if refused (reason).
Procedure.q Push(*Client.EdgeClient, Topic.s, Json.s, UploadId.q, *Reason.String)
Protected Push.BakaShrot_PushMessage, *Pushed.BakaShrot_MessagePushed
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Id.q
*Reason\s = ""
Push\Topic = Topic
Push\JsonData = Json
Push\UploadId = UploadId
*Packet = BakaShrot_PushMessagePacket_Encode(@Push, @PacketSize)
*Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize)
If Not *Answer
*Reason\s = "the link failed"
ProcedureReturn 0
EndIf
If Type\i = #BakaShrot_PacketType_RequestRefused
*Reason\s = Refusal(*Answer, AnswerSize\i)
ElseIf Type\i = #BakaShrot_PacketType_MessagePushed
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
*Pushed = BakaShrot_MessagePushedPacket_Decode(*View)
MsgPackFree(*View, #False)
If *Pushed
Id = *Pushed\MessageId
FreeStructure(*Pushed)
EndIf
EndIf
FreeMemory(*Answer)
ProcedureReturn Id
EndProcedure
; Asks for a part. Returns it (free with _Free), 0 if refused (reason).
Procedure.i GetChunk(*Client.EdgeClient, Topic.s, Node.s, MessageId.q, Index.i, *Reason.String)
Protected Request.BakaShrot_GetAttachment, *Chunk.BakaShrot_AttachmentChunk
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData
*Reason\s = ""
Request\Topic = Topic
Request\Node = Node
Request\MessageId = MessageId
Request\ChunkIndex = Index
*Packet = BakaShrot_GetAttachmentPacket_Encode(@Request, @PacketSize)
*Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize)
If Not *Answer
*Reason\s = "the link failed"
ProcedureReturn 0
EndIf
If Type\i = #BakaShrot_PacketType_RequestRefused
*Reason\s = Refusal(*Answer, AnswerSize\i)
ElseIf Type\i = #BakaShrot_PacketType_AttachmentChunk
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
*Chunk = BakaShrot_AttachmentChunkPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Answer)
ProcedureReturn *Chunk
EndProcedure
; Size random bytes.
Procedure.i RandomBytes(Size.i)
Protected *Data = AllocateMemory(Size)
RandomData(*Data, Size)
ProcedureReturn *Data
EndProcedure
Procedure Sha256Of(*Data, Size.q, *Out)
Protected Hash.BakaShrot_Sha256
BakaShrot_Sha256_Start(@Hash)
BakaShrot_Sha256_Add(@Hash, *Data, Size)
BakaShrot_Sha256_Finish(@Hash, *Out)
EndProcedure
; Uploads Size bytes of *Data properly. Returns the upload id, 0 on failure.
Procedure.q UploadAll(*Client.EdgeClient, Topic.s, *Data, Size.q)
Protected Dim Sha.a(31), Id.q, Index.i, Complete.Integer, Reason.String
Sha256Of(*Data, Size, @Sha(0))
Id = StartUpload(*Client, Topic, Size, @Sha(0), @Reason)
If Not Id
ProcedureReturn 0
EndIf
For Index = 0 To BakaShrot_AttachmentChunkCount(Size) - 1
If SendChunk(*Client, Id, Index, *Data + Index * #BakaShrot_AttachmentChunkSize, BakaShrot_AttachmentChunkBytes(Size, Index), @Complete, @Reason) <> 1
ProcedureReturn 0
EndIf
Next
If Not Complete\i
ProcedureReturn 0
EndIf
ProcedureReturn Id
EndProcedure
Define Kitchen.EdgeClient, Garage.EdgeClient, Reason.String, Complete.Integer
Define Dim Sha.a(31), Dim WrongSha.a(31)
Define *Data, *Other, Id.q, Id2.q, MessageId.q, Result.i, *Chunk.BakaShrot_AttachmentChunk, Size.q
Define PartialId.q, CompleteId.q
OpenConsole()
If CountProgramParameters() < 3
PrintN("Usage: AttachmentEdgeClient edge <KitchenIni> <GarageIni> | late <KitchenIni> <PartialId> <CompleteId>")
End 1
EndIf
If Not ConnectIni(@Kitchen, ProgramParameter(1))
PrintN("FAIL can't connect with " + ProgramParameter(1))
End 1
EndIf
If LCase(ProgramParameter(0)) = "late"
PartialId = Val(ProgramParameter(2))
CompleteId = Val(ProgramParameter(3))
*Data = RandomBytes(#BakaShrot_AttachmentChunkSize)
Result = SendChunk(@Kitchen, PartialId, 1, *Data, 1000, @Complete, @Reason)
Check("An expired upload: its next part refused", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s)
MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "late" + Chr(34) + ":1}", CompleteId, @Reason)
Check("An expired complete upload: pushing with it refused", Bool(MessageId = 0 And (FindString(Reason\s, "No such upload") Or FindString(Reason\s, "isn't complete"))), Reason\s)
Check("Still connected after the refusals", BakaShrot_Outbound_IsConnected(@Kitchen\Outbound))
BakaShrot_Outbound_Close(@Kitchen\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
PrintN("")
If Fails : PrintN(Str(Fails) + " FAILED") : End 1 : EndIf
PrintN("All passed")
End 0
EndIf
If Not ConnectIni(@Garage, ProgramParameter(2))
PrintN("FAIL can't connect with " + ProgramParameter(2))
End 1
EndIf
; --- A wrong SHA-256 --------------------------------------------------------------
Size = #BakaShrot_AttachmentChunkSize + 500000
*Data = RandomBytes(Size)
*Other = RandomBytes(Size)
Sha256Of(*Other, Size, @WrongSha(0))
Id = StartUpload(@Kitchen, "logs", Size, @WrongSha(0), @Reason)
Check("Upload with a wrong SHA-256: started", Bool(Id > 0), Reason\s)
Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
Check(" part 0 stored, not complete", Bool(Result = 1 And Complete\i = 0), Reason\s)
Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, 500000, @Complete, @Reason)
Check(" the last part: refused, doesn't match", Bool(Result = 0 And FindString(Reason\s, "doesn't match its SHA-256")), Reason\s)
MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "bad" + Chr(34) + ":1}", Id, @Reason)
Check(" pushing with it: refused", Bool(MessageId = 0 And FindString(Reason\s, "isn't complete")), Reason\s)
Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, 500000, @Complete, @Reason)
Check(" sending the last part again: refused, it's dropped", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s)
; --- Parts out of order, wrong size, repeated ---------------------------------------
Size = 2 * #BakaShrot_AttachmentChunkSize + 1234
FreeMemory(*Data) : *Data = RandomBytes(Size)
Sha256Of(*Data, Size, @Sha(0))
Id = StartUpload(@Kitchen, "logs", Size, @Sha(0), @Reason)
Check("Upload of 3 parts: started", Bool(Id > 0), Reason\s)
Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
Check(" part 1 first: refused", Bool(Result = 0 And FindString(Reason\s, "Expected part 0 of 3")), Reason\s)
Result = SendChunk(@Kitchen, Id, 0, *Data, 1000, @Complete, @Reason)
Check(" part 0 too short: refused", Bool(Result = 0 And FindString(Reason\s, "1048576 bytes")), Reason\s)
Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
Check(" part 0 right: stored, the refusals didn't drop the upload", Bool(Result = 1 And Complete\i = 0), Reason\s)
Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
Check(" part 0 again: refused", Bool(Result = 0 And FindString(Reason\s, "Expected part 1")), Reason\s)
Result = SendChunk(@Garage, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
Check(" part 1 from another client: refused", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s)
Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
Check(" part 1: stored", Bool(Result = 1 And Complete\i = 0), Reason\s)
Result = SendChunk(@Kitchen, Id, 2, *Data + 2 * #BakaShrot_AttachmentChunkSize, 1234, @Complete, @Reason)
Check(" part 2, the last: complete", Bool(Result = 1 And Complete\i = 1), Reason\s)
Result = SendChunk(@Kitchen, Id, 3, *Data, 10, @Complete, @Reason)
Check(" a part past the end: refused", Bool(Result = 0), Reason\s)
; --- Whose, which topic, how many times -------------------------------------------------
MessageId = Push(@Garage, "logs", "{" + Chr(34) + "theirs" + Chr(34) + ":1}", Id, @Reason)
Check("Another client pushing with it: refused", Bool(MessageId = 0 And FindString(Reason\s, "No such upload")), Reason\s)
MessageId = Push(@Kitchen, "other", "{" + Chr(34) + "topic" + Chr(34) + ":1}", Id, @Reason)
Check("Pushing it to another topic: refused", Bool(MessageId = 0 And FindString(Reason\s, "is for topic 'logs'")), Reason\s)
MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":1}", Id, @Reason)
Check("Pushing it: stored", Bool(MessageId > 0), "message #" + Str(MessageId) + " " + Reason\s)
Id2 = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":2}", Id, @Reason)
Check("Pushing it again: refused, attached already", Bool(Id2 = 0 And FindString(Reason\s, "attached already")), Reason\s)
Id2 = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":3}", 999999, @Reason)
Check("An upload id that doesn't exist: refused", Bool(Id2 = 0 And FindString(Reason\s, "No such upload")), Reason\s)
; --- Reading it back, part by part ---------------------------------------------------------
*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 2, @Reason)
Check("GetAttachment part 2 first: the right bytes", Bool(*Chunk And *Chunk\DataSize = 1234 And *Chunk\Size = Size And CompareMemory(*Chunk\Data, *Data + 2 * #BakaShrot_AttachmentChunkSize, 1234) And CompareMemory(@*Chunk\Sha256[0], @Sha(0), 32)), Reason\s)
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 0, @Reason)
Check(" part 0: the right bytes", Bool(*Chunk And *Chunk\DataSize = #BakaShrot_AttachmentChunkSize And CompareMemory(*Chunk\Data, *Data, #BakaShrot_AttachmentChunkSize)), Reason\s)
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 3, @Reason)
Check(" part 3, past the end: refused", Bool(Not *Chunk And FindString(Reason\s, "has 3 parts")), Reason\s)
*Chunk = GetChunk(@Garage, "secret", "kitchen", MessageId, 0, @Reason)
Check(" from a topic garage may not read: refused", Bool(Not *Chunk And FindString(Reason\s, "Not allowed to read topic")), Reason\s)
; --- Limits ------------------------------------------------------------------------------------
Id = StartUpload(@Kitchen, "logs", 1024 * 1024 * 1024, @Sha(0), @Reason)
Check("Upload of 1 GB (over MaxAttachmentSize): refused", Bool(Id = 0 And FindString(Reason\s, "too big")), Reason\s)
Id = StartUpload(@Garage, "other", 1000, @Sha(0), @Reason)
Check("Upload to a topic garage may not push to: refused", Bool(Id = 0 And FindString(Reason\s, "Not allowed to push")), Reason\s)
Check("Both still connected after every refusal", Bool(BakaShrot_Outbound_IsConnected(@Kitchen\Outbound) And BakaShrot_Outbound_IsConnected(@Garage\Outbound)))
; --- Left behind, for the expiry ---------------------------------------------------------------------
Size = 2 * #BakaShrot_AttachmentChunkSize
FreeMemory(*Data) : *Data = RandomBytes(Size)
Sha256Of(*Data, Size, @Sha(0))
PartialId = StartUpload(@Kitchen, "logs", Size, @Sha(0), @Reason)
Result = SendChunk(@Kitchen, PartialId, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
CompleteId = UploadAll(@Kitchen, "logs", *Data, 5000)
Check("Two uploads left behind: half sent, and complete but never pushed", Bool(PartialId > 0 And Result = 1 And CompleteId > 0), Str(PartialId) + ", " + Str(CompleteId))
BakaShrot_Outbound_Close(@Kitchen\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
BakaShrot_Outbound_Close(@Garage\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
PrintN("LEFT " + Str(PartialId) + " " + Str(CompleteId))
PrintN("")
If Fails : PrintN(Str(Fails) + " FAILED") : End 1 : EndIf
PrintN("All passed")
End 0
+292
View File
@@ -0,0 +1,292 @@
# The attachment cases the regular clients never produce (Design/Attachments.md):
# 1. Through a raw client (Tests/AttachmentEdgeClient.pb): a wrong SHA-256,
# parts out of order / of the wrong size / repeated, someone else's
# upload, the wrong topic, an upload attached twice, too big, a part
# out of range.
# 2. Uploads left behind: kept within UploadTimeout, deleted past it, then
# refused.
# 3. Replication resuming: the receiving server killed in the middle of a
# 400 MB attachment, restarted, the sender goes on from where it stopped.
# 4. A corrupted attachment (bytes flipped in the sender's database): the
# client refuses it, the peer drops it and doesn't keep it.
# Two servers, A (port 12413) and B (12414). Needs Build\ (Build.ps1),
# Build\Bench\BenchServer.exe, Build\AttachmentEdgeClient.exe (compile
# Tests\AttachmentEdgeClient.pb, thread-safe console), and Python 3 for 4.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\AttachmentEdges-Test.ps1 [-Python <python.exe>]
param(
[string]$Build = (Join-Path $PSScriptRoot "..\Build"),
[string]$Python = "python"
)
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_attachedges"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Fails = 0
function New-KeyPair {
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
$C = New-Object System.Net.Sockets.TcpClient
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
}
function Tool([string]$Name, [string[]]$A) {
$O = & (Join-Path $Build $Name) @A 2>&1
@{ Code = $LASTEXITCODE; Out = ($O -join " | "); Lines = @($O) }
}
function Check([string]$What, [bool]$Ok, [string]$Detail) {
if (-not $Ok) { $script:Fails++ }
"{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail
}
function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) {
Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out)
}
function Start-Srv($Name) {
$Stop = Join-Path $Dir "$Name.stop"
Remove-Item $Stop -ErrorAction SilentlyContinue
# Each run its own log: a restart doesn't overwrite the last one's.
$script:Runs[$Name]++
$Log = Join-Path $Dir "$Name.$($script:Runs[$Name]).log"
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput $Log -WindowStyle Hidden -PassThru
$null = $P.Handle
@{ P = $P; Stop = $Stop; Name = $Name; Log = $Log }
}
$Runs = @{ a = 0; b = 0 }
function Stop-Srv($S) {
if (-not $S -or $S.P.HasExited) { return }
Set-Content $S.Stop "x"
if (-not $S.P.WaitForExit(30000)) { Stop-Process -Id $S.P.Id -Force }
}
function Wait-Port($Port, $S) {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content $S.Log -Raw)" }
if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" }
Start-Sleep -Milliseconds 100
}
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
}
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
$D = (Get-Date).AddSeconds($Seconds)
do {
$R = Query $Sql $Ini
if ($R.Code -eq 0 -and $R.Out -match $Pattern) { return $R }
Start-Sleep -Milliseconds 250
} while ((Get-Date) -lt $D)
$R
}
function Push($Data, $Ini, [string]$Attach = "") {
$F = Join-Path $Dir "push.txt"
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
$A = @()
if ($Attach) { $A += @("-a", $Attach) }
Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini))
}
function New-File($Name, [int64]$Size, [int]$Seed) {
$P = Join-Path $Dir $Name
$R = New-Object System.Random $Seed
$Buf = New-Object byte[] ([math]::Min($Size, 16MB))
$F = [IO.File]::OpenWrite($P)
$Left = $Size
while ($Left -gt 0) { $R.NextBytes($Buf); $N = [math]::Min($Left, $Buf.Length); $F.Write($Buf, 0, $N); $Left -= $N }
$F.Close()
$P
}
function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA256).Hash } else { "no file" } }
function Num($Out) { if ($Out -match '\[\["(\d+)"\]\]') { [int64]$Matches[1] } else { -1 } }
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair
foreach ($Name in "a", "b") {
$Me = @{ a = $A; b = $B }[$Name]; $Peer = @{ a = $B; b = $A }[$Name]
$PeerName = @{ a = "b"; b = "a" }[$Name]
$Port = @{ a = 12413; b = 12414 }[$Name]; $PeerPort = @{ a = 12414; b = 12413 }[$Name]
$Base = @{ a = 1; b = 100 }[$Name]
Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($Me.Priv)
Node = server$Name
[BakaShrot.Topics]
logs = $Base
other = $($Base + 1)
secret = $($Base + 2)
[BakaShrot.Nodes]
servera = $($Base + 10)
serverb = $($Base + 11)
kitchen = $($Base + 2)
garage = $($Base + 3)
[BakaShrot.Server]
Host = 127.0.0.1
Port = $Port
ReplicatingTopics = logs
DatabasePath = $(Join-Path $Dir "$Name.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
RetentionInterval = 1
MaxAttachmentSize = 512M
UploadTimeout = 10
[BakaShrot.Peer.$PeerName]
Host = 127.0.0.1
Port = $PeerPort
Node = server$PeerName
PublicKey = $($Peer.Pub)
[BakaShrot.Client.$PeerName]
PublicKeys = $($Peer.Pub)
Node = server$PeerName
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Node = kitchen
DefaultTopic = logs
PushTopics = logs;other;secret
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.garage]
PublicKeys = $($G.Pub)
Node = garage
DefaultTopic = logs
PushTopics = logs
ReadTopics = logs
"@
}
$ServerKeys = @{ 12413 = $A.Pub; 12414 = $B.Pub }
function Client-Ini($Name, $Keys, $Node, $Port) {
$P = Join-Path $Dir "$Name.ini"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
$P
}
$KitchenA = Client-Ini "kitchen-a" $K "kitchen" 12413
$GarageA = Client-Ini "garage-a" $G "garage" 12413
$KitchenB = Client-Ini "kitchen-b" $K "kitchen" 12414
foreach ($Port in 12413, 12414) { if (Test-Port $Port) { throw "Port $Port is already in use" } }
$SA = Start-Srv "a"; $SB = $null
try {
Wait-Port 12413 $SA
"--- 1. Through the raw client"
$R = Tool "AttachmentEdgeClient.exe" @("edge", $KitchenA, $GarageA)
$R.Lines | Where-Object { $_ -match "^(PASS|FAIL| ->)" }
$Script:Fails += @($R.Lines | Where-Object { $_ -match "^FAIL" }).Count
Check "the raw client ran to the end" ($R.Code -ne $null -and ($R.Out -match "LEFT (\d+) (\d+)")) $R.Lines[-1]
$Partial = $Matches[1]; $Complete = $Matches[2]
$LeftAt = Get-Date
"--- 2. Uploads left behind (UploadTimeout = 10)"
$Sql = "SELECT blob_id, state, received FROM blobs WHERE blob_id IN ($Partial, $Complete) ORDER BY blob_id"
$R = Query $Sql $KitchenA
Check "within UploadTimeout: both kept, receiving (0) and complete (1)" ($R.Out -match "\[\[`"$Partial`",`"0`",`"1048576`"\],\[`"$Complete`",`"1`",`"5000`"\]\]") $R.Out
$R = Wait-Query "SELECT COUNT(*) FROM blobs WHERE blob_id IN ($Partial, $Complete)" $KitchenA '\[\["0"\]\]' 25
$After = ((Get-Date) - $LeftAt).TotalSeconds
Check "past it: both deleted" ($R.Out -match '\[\["0"\]\]') ("{0:N1} s after they were left" -f $After)
Check " not before 10 s" ($After -ge 8) ("{0:N1} s" -f $After)
Expect " their parts too" (Query "SELECT COUNT(*) FROM blob_chunks WHERE blob_id IN ($Partial, $Complete)" $KitchenA) '\[\["0"\]\]'
Expect " and the one with the wrong SHA-256 (dropped at once)" (Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenA) '\[\["0"\]\]'
Expect " the attached one is kept" (Query "SELECT COUNT(*) FROM blobs WHERE state = 2" $KitchenA) '\[\["1"\]\]'
$R = Tool "AttachmentEdgeClient.exe" @("late", $KitchenA, $Partial, $Complete)
$R.Lines | Where-Object { $_ -match "^(PASS|FAIL| ->)" }
$Script:Fails += @($R.Lines | Where-Object { $_ -match "^FAIL" }).Count
"--- 3. Replication resuming (B killed in the middle of 400 MB)"
$Big = New-File "big.bin" 400MB 9
$R = Push '{"big":1}' $KitchenA $Big
Check "push 400 MB to A" ($R.Code -eq 0 -and $R.Out -match "message #(\d+), with an attachment") $R.Out
$BigId = $Matches[1]
$SB = Start-Srv "b"
Wait-Port 12414 $SB
$Received = "SELECT COALESCE(MAX(b.received), 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id LEFT JOIN blobs b ON b.blob_id = a.blob_id WHERE t.name = 'logs' AND a.message_id = $BigId"
$KilledAt = -1
$D = (Get-Date).AddSeconds(60)
while ((Get-Date) -lt $D) {
$N = Num (Query $Received $KitchenB).Out
if ($N -ge 40MB) { Stop-Process -Id $SB.P.Id -Force; $SB.P.WaitForExit(10000) | Out-Null; $KilledAt = $N; break }
Start-Sleep -Milliseconds 50
}
Check "B killed in the middle" ($KilledAt -gt 0 -and $KilledAt -lt 400MB) ("{0:N0} MB of 400 received" -f ($KilledAt / 1MB))
$SB = Start-Srv "b"
Wait-Port 12414 $SB
$AfterRestart = Num (Query $Received $KitchenB).Out
Check "after the restart, what it had is still there" ($AfterRestart -ge $KilledAt) ("{0:N0} MB" -f ($AfterRestart / 1MB))
$Copy = Join-Path $Dir "big-from-b.bin"
$D = (Get-Date).AddSeconds(90)
do {
$R = Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BigId, $Copy, $KitchenB)
if ($R.Code -eq 0) { break }
Start-Sleep -Milliseconds 500
} while ((Get-Date) -lt $D)
Check "B ends up with all of it, identical" ($R.Code -eq 0 -and (Hash $Copy) -eq (Hash $Big)) $R.Out
$LogA = (Get-ChildItem $Dir -Filter "a.*.log" | ForEach-Object { Get-Content $_.FullName -Raw }) -join "`n"
$Resumed = [regex]::Matches($LogA, "Sent the attachment of logs:kitchen#$BigId to 'b' in \d+ ms, from part (\d+)")
$From = if ($Resumed.Count) { [int]$Resumed[$Resumed.Count - 1].Groups[1].Value } else { -1 }
Check "A went on from where B stopped, not from 0" ($From -gt 0 -and $From * 1MB -le $AfterRestart) ("from part $From, B had {0:N0} MB" -f ($AfterRestart / 1MB))
Remove-Item $Copy, $Big -ErrorAction SilentlyContinue
"--- 4. A corrupted attachment"
$HasPython = $false
try { & $Python -c "import sqlite3" 2>&1 | Out-Null; $HasPython = ($LASTEXITCODE -eq 0) } catch { }
if (-not $HasPython) {
"SKIP no Python ($Python)"
} else {
Stop-Srv $SB; $SB = $null
$Small = New-File "small.bin" (3MB + 99) 10
$R = Push '{"corrupt":1}' $KitchenA $Small
Check "push 3 MB to A, B stopped" ($R.Code -eq 0 -and $R.Out -match "message #(\d+), with an attachment") $R.Out
$BadId = $Matches[1]
Stop-Srv $SA
$Flip = @"
import sqlite3, sys
db = sqlite3.connect(sys.argv[1])
row = db.execute("SELECT c.rowid, c.chunk_data FROM blob_chunks c JOIN attachments a ON a.blob_id = c.blob_id WHERE a.message_id = ? AND a.topic_id = 1 AND c.chunk_index = 1", (int(sys.argv[2]),)).fetchone()
data = bytearray(row[1]); data[1000] ^= 0xFF
db.execute("UPDATE blob_chunks SET chunk_data = ? WHERE rowid = ?", (bytes(data), row[0]))
db.commit(); print("flipped")
"@
Set-Content (Join-Path $Dir "flip.py") -Encoding Ascii -Value $Flip
$Out = & $Python -B (Join-Path $Dir "flip.py") (Join-Path $Dir "a.sqlite") $BadId 2>&1
Check "a byte flipped in A's database, part 1" ("$Out" -eq "flipped") "$Out"
$SA = Start-Srv "a"
Wait-Port 12413 $SA
$Copy = Join-Path $Dir "bad-from-a.bin"
Expect "reading it from A: the client refuses it" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenA)) "doesn't match its SHA-256" 1
Check " and leaves no file" (-not (Test-Path $Copy)) "checked"
$SB = Start-Srv "b"
Wait-Port 12414 $SB
Start-Sleep -Seconds 6
$LogB = Get-Content $SB.Log -Raw
$Drops = [regex]::Matches($LogB, "attachment of logs:kitchen#$BadId from peer 'a' doesn't match its SHA-256, dropped").Count
Check "B drops it: doesn't match" ($Drops -ge 1) "$Drops times in 6 s"
Expect "B doesn't serve it" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenB)) "isn't here yet" 1
# A sends it again at every check-in, so B can be receiving (1) it
# again when asked: back to missing once that copy is dropped too.
$R = Wait-Query "SELECT a.state, COALESCE(a.blob_id, 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' AND a.message_id = $BadId" $KitchenB '\[\["0","0"\]\]' 5
Check "B's attachment is back to missing (0), no blob" ($R.Out -match '\[\["0","0"\]\]') $R.Out
Expect "B: no blob left behind, once cleaned" (Wait-Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenB '\[\["0"\]\]' 5) '\[\["0"\]\]'
"INFO A sends it again at every check-in: $Drops times in 6 s (PeerSyncInterval 1)"
}
}
finally {
Stop-Srv $SA; Stop-Srv $SB
}
"--- Logs"
# Refusals are what this test asks for, their codes' names (InvalidRequest)
# aren't bad packets.
$All = (Get-ChildItem $Dir -Filter "*.log" | ForEach-Object { Get-Content $_.FullName }) | Where-Object { $_ -notmatch "Refused a request" -and $_ -match "invalid|unexpected|doesn't decrypt" }
Check "no invalid or unexpected packets in any log" ($All.Count -eq 0) ($All -join " / ")
""
if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" }
+306
View File
@@ -0,0 +1,306 @@
# End-to-end test of attachments (Design/Attachments.md), through the tools
# (BakaShrotPushMessage -a, BakaShrotGetAttachment, BakaShrotGetLatestMessage):
# - pushed with a message, read back identical (100 KB, 5 MB + a bit,
# exactly 2 MB: one part, several, a whole number of them);
# - a message without one: refused when asked for it;
# - replicated after their messages, identical on the other server;
# - bigger than the other server's MaxAttachmentSize: its message comes,
# the attachment is refused there as not kept;
# - too big to push: refused, and the message isn't stored;
# - deleted with their message by the retention, parts included.
# Two linked servers, A (port 12410, MaxAttachmentSize 64M) and B (12411, 3M).
# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\Attachments-Test.ps1
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"))
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_attachtest"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Fails = 0
function New-KeyPair {
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
$C = New-Object System.Net.Sockets.TcpClient
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
}
function Tool([string]$Name, [string[]]$A) {
$O = & (Join-Path $Build $Name) @A 2>&1
@{ Code = $LASTEXITCODE; Out = ($O -join " | ") }
}
function Check([string]$What, [bool]$Ok, [string]$Detail) {
if (-not $Ok) { $script:Fails++ }
"{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail
}
function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) {
Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out)
}
function Start-Srv($Name) {
$Stop = Join-Path $Dir "$Name.stop"
Remove-Item $Stop -ErrorAction SilentlyContinue
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput (Join-Path $Dir "$Name.log") -WindowStyle Hidden -PassThru
$null = $P.Handle
@{ P = $P; Stop = $Stop; Name = $Name }
}
function Stop-Srv($S) {
if ($S.P.HasExited) { return }
Set-Content $S.Stop "x"
if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force }
}
function Wait-Port($Port, $S) {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content (Join-Path $Dir "$($S.Name).log") -Raw)" }
if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" }
Start-Sleep -Milliseconds 100
}
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
}
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
$D = (Get-Date).AddSeconds($Seconds)
do {
$R = Query $Sql $Ini
if ($R.Code -eq 0 -and $R.Out -match $Pattern) { return $R }
Start-Sleep -Milliseconds 250
} while ((Get-Date) -lt $D)
$R
}
function Push($Data, $Ini, [string]$Topic = "", [string]$Attach = "") {
$F = Join-Path $Dir "push.txt"
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
$A = @()
if ($Topic) { $A += @("-t", $Topic) }
if ($Attach) { $A += @("-a", $Attach) }
Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini))
}
# A file of Size random bytes.
function New-File($Name, [int]$Size, [int]$Seed) {
$P = Join-Path $Dir $Name
$B = New-Object byte[] $Size
(New-Object System.Random $Seed).NextBytes($B)
[IO.File]::WriteAllBytes($P, $B)
$P
}
function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA256).Hash } else { "no file" } }
# Saves an attachment and compares it with the original.
function Expect-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini) {
$Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin")
$R = Tool "BakaShrotGetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini)
$Same = ($R.Code -eq 0) -and ((Hash $Out) -eq (Hash $Original))
Check $What $Same ("[{0}] {1}" -f $R.Code, $R.Out)
}
# Retries BakaShrotGetAttachment until it works: replicated ones come after their message.
function Wait-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini, $Seconds = 20) {
$Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin")
$D = (Get-Date).AddSeconds($Seconds)
do {
$R = Tool "BakaShrotGetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini)
if ($R.Code -eq 0) { break }
Start-Sleep -Milliseconds 250
} while ((Get-Date) -lt $D)
Check $What (($R.Code -eq 0) -and ((Hash $Out) -eq (Hash $Original))) ("[{0}] {1}" -f $R.Code, $R.Out)
}
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair
Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($A.Priv)
Node = serverA
[BakaShrot.Topics]
logs = 1
short = 2
photos = 3
[BakaShrot.Nodes]
serverA = 10
serverB = 11
kitchen = 2
garage = 3
[BakaShrot.Retention]
short = 4s
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12410
ReplicatingTopics = logs;short;photos
DatabasePath = $(Join-Path $Dir "a.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
RetentionInterval = 1
MaxAttachmentSize = 64M
[BakaShrot.Peer.b]
Host = 127.0.0.1
Port = 12411
Node = serverB
PublicKey = $($B.Pub)
[BakaShrot.Client.b]
PublicKeys = $($B.Pub)
Node = serverB
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Node = kitchen
DefaultTopic = logs
PushTopics = logs;short
ReadTopics = *
AllowQuery = 1
"@
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($B.Priv)
Node = serverB
[BakaShrot.Topics]
logs = 300
short = 301
photos = 302
[BakaShrot.Nodes]
serverA = 1
serverB = 2
kitchen = 30
garage = 31
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12411
ReplicatingTopics = logs;short;photos
DatabasePath = $(Join-Path $Dir "b.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
RetentionInterval = 1
MaxAttachmentSize = 3M
[BakaShrot.Peer.a]
Host = 127.0.0.1
Port = 12410
Node = serverA
PublicKey = $($A.Pub)
[BakaShrot.Client.a]
PublicKeys = $($A.Pub)
Node = serverA
DefaultTopic = logs
[BakaShrot.Client.garage]
PublicKeys = $($K.Pub)
Node = garage
DefaultTopic = photos
PushTopics = photos
ReadTopics = *
AllowQuery = 1
"@
$ServerKeys = @{ 12410 = $A.Pub; 12411 = $B.Pub }
function Client-Ini($Name, $Topic, $Node, $Port) {
$P = Join-Path $Dir "$Name.ini"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
$P
}
$OnA = Client-Ini "kitchen-a" "logs" "kitchen" 12410
$OnB = Client-Ini "garage-b" "photos" "garage" 12411
$Small = New-File "small.bin" (100 * 1024) 1
$Mid = New-File "mid.bin" (5 * 1024 * 1024 + 123) 2
$Exact = New-File "exact.bin" (2 * 1024 * 1024) 3
$Tiny = New-File "tiny.bin" 1 4
foreach ($Port in 12410, 12411) { if (Test-Port $Port) { throw "Port $Port is already in use" } }
$SA = Start-Srv "a"; $SB = Start-Srv "b"
try {
Wait-Port 12410 $SA; Wait-Port 12411 $SB
Start-Sleep -Seconds 1
"--- Pushed with their message, read back"
Expect "push #1 with 100 KB" (Push '{"n":1}' $OnA "" $Small) "message #1, with an attachment of 102400 bytes"
$Started = Get-Date
Expect "push #2 with 5 MB + 123 bytes (6 parts)" (Push '{"n":2}' $OnA "" $Mid) "message #2, with an attachment of 5243003 bytes"
$UploadMs = ((Get-Date) - $Started).TotalMilliseconds
Expect "push #3 with exactly 2 MB (2 parts)" (Push '{"n":3}' $OnA "" $Exact) "message #3, with an attachment of 2097152 bytes"
Expect "push #4 with 1 byte" (Push '{"n":4}' $OnA "" $Tiny) "message #4"
Expect "push #5 without" (Push '{"n":5}' $OnA) "message #5$"
Expect-Same "#1 read back identical" "logs" "kitchen" 1 $Small $OnA
$Started = Get-Date
Expect-Same "#2 read back identical" "logs" "kitchen" 2 $Mid $OnA
$DownloadMs = ((Get-Date) - $Started).TotalMilliseconds
Check "5 MB up and down, tool start included" $true ("{0:N0} ms up, {1:N0} ms down" -f $UploadMs, $DownloadMs)
Expect-Same "#3 read back identical" "logs" "kitchen" 3 $Exact $OnA
Expect-Same "#4 read back identical" "logs" "kitchen" 4 $Tiny $OnA
Expect "#5 has none: refused" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "5", (Join-Path $Dir "none.bin"), $OnA)) "No attachment for logs:kitchen#5" 1
Check "a refused one leaves no file" (-not (Test-Path (Join-Path $Dir "none.bin"))) "checked"
Expect "a message that doesn't exist: refused" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "99", (Join-Path $Dir "none.bin"), $OnA)) "No attachment" 1
Expect "BakaShrotGetLatestMessage: #5, no attachment line" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnA)) "#5 \(ids 1:2\), pushed [^|]+\| \{`"n`":5\}$"
$R = Query "SELECT message_id, size, state FROM attachments WHERE topic_id = 1 AND node_id = 2 ORDER BY message_id" $OnA
Check "A's attachments: 4, all ready (2)" ($R.Out -match '\[\["1","102400","2"\],\["2","5243003","2"\],\["3","2097152","2"\],\["4","1","2"\]\]') $R.Out
Expect "A stores 6 + 2 + 1 + 1 parts" (Query "SELECT COUNT(*) FROM blob_chunks" $OnA) '\[\["10"\]\]'
"--- Replicated after their messages (B takes up to 3M)"
$R = Wait-Query "SELECT COUNT(*) FROM messages WHERE topic = 'logs' AND node = 'kitchen'" $OnB '\[\["5"\]\]'
Check "B got the 5 messages" ($R.Out -match '\[\["5"\]\]') $R.Out
Wait-Same "B: #1 identical" "logs" "kitchen" 1 $Small $OnB
Wait-Same "B: #3 identical (2 MB)" "logs" "kitchen" 3 $Exact $OnB
Wait-Same "B: #4 identical (1 byte)" "logs" "kitchen" 4 $Tiny $OnB
Expect "B: #2 isn't kept (5 MB > 3M)" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "2", (Join-Path $Dir "none.bin"), $OnB)) "isn't kept here" 1
$R = Query "SELECT a.message_id, a.state FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' ORDER BY a.message_id" $OnB
Check "B's attachments: ready, not kept (3), ready, ready" ($R.Out -match '\[\["1","2"\],\["2","3"\],\["3","2"\],\["4","2"\]\]') $R.Out
Expect "B: BakaShrotGetLatestMessage logs:kitchen, #5 has none" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnB)) "#5 \(ids 300:30\), pushed [^|]+\| \{`"n`":5\}"
"--- Pushed on B, too big there, then replicated to A"
Expect "B refuses 5 MB (more than 3M)" (Push '{"photo":0}' $OnB "" $Mid) "too big: 5243003 bytes, at most 3145728" 1
Expect "the message wasn't stored: the next is #1" (Push '{"photo":1}' $OnB "" $Small) "message #1, with an attachment"
Wait-Same "A got B's photos:garage#1 identical" "photos" "garage" 1 $Small $OnA
Expect "A: the latest of photos:garage" (Tool "BakaShrotGetLatestMessage.exe" @("photos", "garage", $OnA)) "Attachment: 102400 bytes \| \{`"photo`":1\}"
"--- Deleted with their message (A: short = 4s)"
$Before = (Query "SELECT COUNT(*) FROM blob_chunks" $OnA).Out
Expect "push short #1 with 2 MB" (Push '{"s":1}' $OnA "short" $Exact) "message #1, with an attachment"
Expect "A has 2 more parts" (Query "SELECT COUNT(*) FROM blob_chunks" $OnA) '\[\["13"\]\]'
$R = Wait-Query "SELECT COUNT(*) FROM messages WHERE topic = 'short'" $OnA '\[\["0"\]\]' 15
Check "the message is deleted past 4 s" ($R.Out -match '\[\["0"\]\]') $R.Out
$R = Wait-Query "SELECT COUNT(*) FROM blob_chunks" $OnA '\[\["11"\]\]' 10
Check "and its 2 parts" ($R.Out -match '\[\["11"\]\]') "before $Before, now $($R.Out)"
Expect "and its attachments row" (Query "SELECT COUNT(*) FROM attachments WHERE topic_id = 2" $OnA) '\[\["0"\]\]'
Expect "and its blob" (Query "SELECT COUNT(*) FROM blobs WHERE state = 3" $OnA) '\[\["0"\]\]'
Wait-Same "B kept short#1 (no max age there)" "short" "kitchen" 1 $Exact $OnB
}
finally {
Stop-Srv $SA; Stop-Srv $SB
}
"--- Logs"
# A and B start together: until its first link, the other one may not be
# listening yet. Refused at once on Linux, while Windows retries the connect
# for about a second, by which time it usually is. Those attempts are left out.
function Skip-EarlyLinkFailures([string[]]$Lines) {
$Linked = $false
foreach ($Line in $Lines) {
if ($Line -match "^\[Peer\] Linked to") { $Linked = $true }
if ($Linked -or $Line -notmatch "^\[Peer\] (Failed to link|Retrying)") { $Line }
}
}
$LogA = @(Skip-EarlyLinkFailures (Get-Content (Join-Path $Dir "a.log"))) -join "`n"
$LogB = @(Skip-EarlyLinkFailures (Get-Content (Join-Path $Dir "b.log"))) -join "`n"
Check "A sent B the attachments it takes" ($LogA -match "Sent the attachment of logs:kitchen#1 to 'b'" -and $LogA -match "Sent the attachment of logs:kitchen#3 to 'b'") "checked"
Check "A never sent #2 (not kept by B)" (-not ($LogA -match "Sent the attachment of logs:kitchen#2")) "checked"
Check "B sent A its photo" ($LogB -match "Sent the attachment of photos:garage#1 to 'a'") "checked"
Check "A logged deleting the parts" ($LogA -match "deleted 2 attachment parts") "checked"
$Other = ($LogA + "`n" + $LogB) -split "`r?`n" | Where-Object { $_ -match "Failed|invalid|unexpected|doesn't decrypt|SHA-256" -and $_ -notmatch "Refused a request" }
Check "no failure in A's or B's log" ($Other.Count -eq 0) ($Other -join " / ")
""
if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" }
+666
View File
@@ -0,0 +1,666 @@
# ============================================================================
# BakaShrot replication benchmark
#
# Runs several servers linked as peers on localhost (by default 4 in a Y: one
# hub linked to 3 leaves), each with its own nodes pushing to it, and
# measures, stage by stage:
# - the push path: achieved vs offered rate, latency, failures
# - replication: lag on every server while pushing, whether it keeps up
# (trough slope, see Bench_TroughSlope() in BenchClient.pb), and how long
# it takes to drain once the pushes stop
# - every server's CPU and RAM, and its database's size
# - a query suite (queries.txt) after every stage, as the data grows
#
# Three parts:
# 1. Ramp: from an empty database, stages of -Ramp ("NodesxRate", Rate per
# node in msg/s, 0 = as fast as the server answers), to find where the
# push path and the replication saturate.
# 2. Scale: seeds every database up to each of -SeedTotals rows (identical
# on every server, see BenchSeed.pb), then runs -SteadyStage and the
# query suite at that size: how check-ins and queries hold up with
# lots of data.
# 3. Mixed: -MixedStage with queries_load.txt running in a loop against
# the hub meanwhile: reads under write load, and writes under reads.
#
# Results go into Build\Bench\runs\<timestamp>\: configs, per-stage samples
# (CSV, one row per sample), summaries (JSON), and report.md / results.json
# for the whole run.
# The databases and server logs go into -DataDir\<timestamp>\ instead, out of
# the repo: every push rewrites them, and file watchers on the repo (git
# caches, editors) otherwise burn a core or two reacting to it, skewing the
# CPU numbers. The databases are deleted at the end, unless -KeepData.
#
# Usage:
# powershell -ExecutionPolicy Bypass -File Tests\Bench\Bench-Replication.ps1
# ... -Ramp "5x20,10x50" -SeedTotals @() -PushSeconds 10 quick run
# ... -Topology Mesh -PeerSyncInterval 1 variations
# ... -Synchronous NORMAL the servers' Synchronous (FULL by default)
# ... -Names Wildcard each server only names its own nodes, and
# takes the others' by AcceptNodes = n*
# ... -Parts Ramp only part 1
# Keep -PushSeconds at 6+ times PeerSyncInterval for the trough slope to mean
# something.
#
# ... -Compiler "C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe" `
# -CompilerFlags "/OPTIMIZER" PB 6.40, C backend
#
# Needs: PureBasic 5.73 x64 (found by itself, or -Compiler), libsodium
# extracted in Libs\libsodium\x64 (see Build.ps1), and a sqlite3.dll with
# the JSON functions (3.38+): Libs\sqlite\x64\sqlite3.dll by default, or
# -SqliteDll.
# Everything runs on one machine: the load generator competes with the
# servers for the CPU, its own CPU use is in the report.
# ============================================================================
param(
[ValidateSet("Y", "Chain", "Mesh")]
[string]$Topology = "Y",
[ValidateSet("Declared", "Wildcard")]
[string]$Names = "Declared",
[int]$ServerCount = 4,
[int]$MaxNodesPerServer = 10,
[int]$MessageSize = 200,
[int]$PushSeconds = 30,
[int]$PeerSyncInterval = 5,
[int]$PeerBatchSize = 100,
# The servers' [BakaShrot.Server] Synchronous: FULL like their default,
# NORMAL to compare with the runs from before 2026-11-09.
[ValidateSet("FULL", "NORMAL")]
[string]$Synchronous = "FULL",
[int]$PortBase = 13001,
[string]$Ramp = "5x5,5x20,5x50,5x100,5x0,10x20,10x50,10x100,10x0",
[int[]]$SeedTotals = @(250000, 1000000),
[string]$SteadyStage = "10x10",
[string]$MixedStage = "10x10",
[string]$Parts = "Ramp,Scale,Mixed",
[int]$QueryRepeats = 3,
[int]$DrainTimeout = 180,
[string]$Compiler = "",
[string]$CompilerFlags = "",
[string]$SqliteDll = "",
[string]$DataDir = (Join-Path ([IO.Path]::GetTempPath()) "BakaShrot-Bench"),
[switch]$KeepData,
[switch]$SkipBuild
)
$ErrorActionPreference = "Stop"
# "Ramp,Scale" or "Ramp", "Scale", from -File or -Command alike.
$PartList = @($Parts -split "[, ]" | ForEach-Object { $_.Trim() } | Where-Object { $_ })
foreach ($Part in $PartList) { if ($Part -notin @("Ramp", "Scale", "Mixed")) { throw "Unknown part $Part, use Ramp, Scale and/or Mixed" } }
$Stamp = Get-Date -Format "yyyyMMdd-HHmmss"
$Root = Resolve-Path (Join-Path $PSScriptRoot "..\..")
$BenchDir = $PSScriptRoot
$OutDir = Join-Path $Root "Build\Bench"
$RunDir = Join-Path $OutDir "runs\$Stamp"
$RunData = Join-Path $DataDir $Stamp
$LogDir = Join-Path $RunData "logs"
$TopicId = 1
# --- Build ------------------------------------------------------------------
function Find-Compiler {
if ($Compiler) { return $Compiler }
foreach ($Candidate in @("C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe",
"C:\Program Files\PureBasic573\Compilers\pbcompiler.exe")) {
if (Test-Path $Candidate) { return $Candidate }
}
throw "PureBasic 5.73 x64 not found, pass -Compiler"
}
function Copy-Dlls {
New-Item -ItemType Directory -Force $OutDir | Out-Null
$Sodium = Join-Path $Root "Libs\libsodium\x64\libsodium.dll"
if (-not (Test-Path $Sodium)) { throw "Missing $Sodium, run Build.ps1 once to extract it" }
Copy-Item $Sodium $OutDir -Force
$Sqlite = $SqliteDll
if (-not $Sqlite) { $Sqlite = Join-Path $Root "Libs\sqlite\x64\sqlite3.dll" }
if (-not (Test-Path $Sqlite)) { throw "Missing $Sqlite, run Build.ps1 once to extract it, or pass -SqliteDll" }
Copy-Item $Sqlite (Join-Path $OutDir "sqlite3.dll") -Force
Write-Host "Using SQLite $((Get-Item $Sqlite).VersionInfo.ProductVersion) from $Sqlite"
}
$script:CompilerName = "(not rebuilt, -SkipBuild)"
function Invoke-Build {
$Pb = Find-Compiler
New-Item -ItemType Directory -Force $OutDir | Out-Null
# "PureBasic 6.40 - C Backend (Windows - x64) - (c) ...", 5.73 takes /EXE,
# 6.x /OUTPUT.
$script:CompilerName = ((& $Pb /VERSION) | Select-Object -First 1) -replace " - \(c\).*$", ""
$OutputFlag = if ($script:CompilerName -match "PureBasic 5\.") { "/EXE" } else { "/OUTPUT" }
$Extra = @($CompilerFlags -split " " | Where-Object { $_ })
if ($Extra.Count -gt 0) { $script:CompilerName += " " + ($Extra -join " ") }
Write-Host "Compiler: $($script:CompilerName)"
foreach ($Item in @(
@("Tests\Bench\BenchServer.pb", "BenchServer.exe", @("/CONSOLE", "/THREAD")),
@("Tests\Bench\BenchClient.pb", "BenchClient.exe", @("/CONSOLE", "/THREAD")),
@("Tests\Bench\BenchSeed.pb", "BenchSeed.exe", @("/CONSOLE")),
@("Tools\BakaShrotGenerateKeyPairs\BakaShrotGenerateKeyPairs.pb", "BakaShrotGenerateKeyPairs.exe", @("/CONSOLE")))) {
Write-Host "Compiling $($Item[0])"
$Flags = $Item[2] + $Extra
& $Pb (Join-Path $Root $Item[0]) @Flags /QUIET $OutputFlag (Join-Path $OutDir $Item[1])
if ($LASTEXITCODE -ne 0) { throw "Failed to compile $($Item[0])" }
}
}
function New-KeyPair {
$Lines = & (Join-Path $OutDir "BakaShrotGenerateKeyPairs.exe")
if ($LASTEXITCODE -ne 0) { throw "BakaShrotGenerateKeyPairs failed: $Lines" }
return @{
PrivateKey = $Lines[0] -replace "^PrivateKey = ", ""
PublicKey = $Lines[1] -replace "^PublicKey = ", ""
}
}
# --- Topology and configs -----------------------------------------------------
function Get-Edges {
$Edges = @()
switch ($Topology) {
"Y" { for ($i = 1; $i -lt $ServerCount; $i++) { $Edges += , @(0, $i) } }
"Chain" { for ($i = 0; $i -lt $ServerCount - 1; $i++) { $Edges += , @($i, ($i + 1)) } }
"Mesh" { for ($i = 0; $i -lt $ServerCount; $i++) { for ($j = $i + 1; $j -lt $ServerCount; $j++) { $Edges += , @($i, $j) } } }
}
return , $Edges
}
function New-Servers {
$Servers = @()
for ($i = 0; $i -lt $ServerCount; $i++) {
if ($Topology -eq "Y") {
if ($i -eq 0) { $Name = "hub" } else { $Name = "leaf$i" }
} else {
$Name = "s$($i + 1)"
}
$Keys = New-KeyPair
$Servers += [pscustomobject]@{
Index = $i
Name = $Name
NodeId = $i + 1
Port = $PortBase + $i
PrivateKey = $Keys.PrivateKey
PublicKey = $Keys.PublicKey
DatabasePath = Join-Path $RunData "$Name.sqlite"
ConfigPath = Join-Path $RunDir "$Name.ini"
StopFile = Join-Path $RunData "$Name.stop"
FirstNode = ($i + 1) * 100 + 1
MonitorNode = 900 + $i + 1
QueryNode = 950 + $i + 1
Peers = @()
Process = $null
}
}
foreach ($Edge in (Get-Edges)) {
$Servers[$Edge[0]].Peers += $Edge[1]
$Servers[$Edge[1]].Peers += $Edge[0]
}
return $Servers
}
function Write-ServerConfig($Server, $Servers, $ClientKeys) {
$LastNode = $Server.FirstNode + $MaxNodesPerServer - 1
# The bench's one key writes as every node: a client section per node.
$ClientSections = (@($Server.FirstNode..$LastNode) + @($Server.MonitorNode, $Server.QueryNode) | ForEach-Object { @"
[BakaShrot.Client.bench$_]
PublicKeys = $($ClientKeys.PublicKey)
Node = $_
DefaultTopic = $TopicId
AllowRead = 1
AllowWrite = 1
AllowQuery = 1
"@ }) -join "`r`n"
# Only named topics and nodes replicate, and they must be named on both
# ends (Declared): every server names every node of every server, with
# the same ids. Wildcard: each server only names its own, the peers take
# them by AcceptNodes = n*, and give them ids of their own. The servers'
# own nodes are named everywhere either way: a peer authenticates by
# name, the others must know it.
$NodeNames = @()
foreach ($Other in $Servers) {
$NodeNames += "n$($Other.NodeId) = $($Other.NodeId)"
if ($Names -eq "Wildcard" -and $Other -ne $Server) { continue }
$OtherLast = $Other.FirstNode + $MaxNodesPerServer - 1
foreach ($Id in (@($Other.FirstNode..$OtherLast) + @($Other.MonitorNode, $Other.QueryNode))) {
$NodeNames += "n$Id = $Id"
}
}
$Text = @"
[BakaShrot]
PrivateKey = $($Server.PrivateKey)
Node = $($Server.NodeId)
[BakaShrot.Topics]
bench = $TopicId
[BakaShrot.Nodes]
$($NodeNames -join "`r`n")
[BakaShrot.Server]
Host = 127.0.0.1
Port = $($Server.Port)
ReplicatingTopics = $TopicId
DatabasePath = $($Server.DatabasePath)
PeerRetryDelay = 2
PeerSyncInterval = $PeerSyncInterval
PeerBatchSize = $PeerBatchSize
Synchronous = $Synchronous
$ClientSections
"@
foreach ($PeerIndex in $Server.Peers) {
$Peer = $Servers[$PeerIndex]
$Text += @"
[BakaShrot.Peer.$($Peer.Name)]
Host = 127.0.0.1
Port = $($Peer.Port)
Node = $($Peer.NodeId)
PublicKey = $($Peer.PublicKey)
$(if ($Names -eq "Wildcard") { "AcceptNodes = n*" })
[BakaShrot.Client.$($Peer.Name)]
PublicKeys = $($Peer.PublicKey)
Node = $($Peer.NodeId)
AllowRead = 0
AllowWrite = 0
AllowQuery = 0
"@
}
Set-Content -Path $Server.ConfigPath -Value $Text -Encoding Ascii
}
# --- Servers ----------------------------------------------------------------
$script:StartCount = 0
function Test-Port($Port) {
$Client = New-Object System.Net.Sockets.TcpClient
try {
$Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null)
if ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected) { return $true }
return $false
} catch {
return $false
} finally {
$Client.Close()
}
}
function Start-Servers($Servers) {
$script:StartCount++
foreach ($Server in $Servers) {
Remove-Item $Server.StopFile -ErrorAction SilentlyContinue
$Log = Join-Path $LogDir "$($Server.Name)-$($script:StartCount).log"
$Server.Process = Start-Process -FilePath (Join-Path $OutDir "BenchServer.exe") `
-ArgumentList "`"$($Server.ConfigPath)`"", "`"$($Server.StopFile)`"" `
-WorkingDirectory $OutDir -NoNewWindow -PassThru `
-RedirectStandardOutput $Log -RedirectStandardError "$Log.err"
}
foreach ($Server in $Servers) {
$Deadline = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Server.Port)) {
if ($Server.Process.HasExited) { throw "$($Server.Name) exited, see its log in $LogDir" }
if ((Get-Date) -gt $Deadline) { throw "$($Server.Name) isn't listening on $($Server.Port)" }
Start-Sleep -Milliseconds 100
}
}
# Let the peers link (they retry every 2 s) and run their first check-in.
Start-Sleep -Seconds 4
Write-Host "Servers up: $(($Servers | ForEach-Object { "$($_.Name)=pid $($_.Process.Id)" }) -join ', ')"
}
function Stop-Servers($Servers) {
foreach ($Server in $Servers) {
if ($Server.Process -and -not $Server.Process.HasExited) {
Set-Content -Path $Server.StopFile -Value "stop"
}
}
foreach ($Server in $Servers) {
if ($Server.Process) {
if (-not $Server.Process.WaitForExit(30000)) {
Write-Warning "$($Server.Name) didn't stop, killing it"
$Server.Process.Kill()
}
$Server.Process = $null
}
}
}
# --- Stages -----------------------------------------------------------------
function ConvertTo-Stage($Spec) {
$Fields = $Spec.Trim().ToLower().Split("x")
return [pscustomobject]@{ Nodes = [int]$Fields[0]; Rate = [double]$Fields[1] }
}
function Write-Plan($Path, $Servers, $ClientKeys, $Stage, $Name, $QueryFile, $QueryLoad) {
$Text = @"
[Bench]
PrivateKey = $($ClientKeys.PrivateKey)
PublicKey = $($ClientKeys.PublicKey)
TopicId = $TopicId
ServerCount = $($Servers.Count)
PushSeconds = $PushSeconds
Rate = $($Stage.Rate)
MessageSize = $MessageSize
SampleMs = 1000
DrainSampleMs = 250
DrainTimeout = $DrainTimeout
PeerSyncInterval = $PeerSyncInterval
SamplesCsv = $(Join-Path $RunDir "$Name.samples.csv")
SummaryOut = $(Join-Path $RunDir "$Name.summary.json")
QueryFile = $QueryFile
QueryRepeats = $QueryRepeats
QueryOut = $(Join-Path $RunDir "$Name.queries.json")
"@
foreach ($Server in $Servers) {
$ProcId = 0
if ($Server.Process) { $ProcId = $Server.Process.Id }
# The query suite runs on the hub and the first leaf, the query load
# only on the hub.
$Text += @"
[Server$($Server.Index + 1)]
Name = $($Server.Name)
Host = 127.0.0.1
Port = $($Server.Port)
PublicKey = $($Server.PublicKey)
Pid = $ProcId
DatabasePath = $($Server.DatabasePath)
FirstNode = $($Server.FirstNode)
MaxNodes = $MaxNodesPerServer
NodeCount = $($Stage.Nodes)
MonitorNode = $($Server.MonitorNode)
QueryNode = $($Server.QueryNode)
QueryLoad = $([int]($QueryLoad -and $Server.Index -eq 0))
Query = $([int]($Server.Index -le 1))
"@
}
Set-Content -Path $Path -Value $Text -Encoding Ascii
}
function Invoke-BenchClient($Mode, $Plan) {
& (Join-Path $OutDir "BenchClient.exe") $Mode $Plan | ForEach-Object { Write-Host " $_" }
if ($LASTEXITCODE -ne 0) { throw "BenchClient $Mode failed" }
}
$script:Results = @()
$script:QueryResults = @()
function Invoke-Stage($Part, $Name, $Stage, $Servers, $ClientKeys, [switch]$QueryLoad) {
$Plan = Join-Path $RunDir "$Name.plan.ini"
$LoadFile = ""
if ($QueryLoad) { $LoadFile = Join-Path $BenchDir "queries_load.txt" }
Write-Plan $Plan $Servers $ClientKeys $Stage $Name $LoadFile $QueryLoad
$RateText = if ($Stage.Rate -gt 0) { "$($Stage.Rate) msg/s" } else { "max" }
Write-Host ""
Write-Host "=== $Name : $($Stage.Nodes) nodes/server x $RateText, $PushSeconds s ===" -ForegroundColor Cyan
# Other processes busy meanwhile (antivirus scanning the databases...),
# tick-based, only good enough to spot the big ones.
$Before = @{}
Get-Process | ForEach-Object { $Before[$_.Id] = $_.CPU }
$StartTime = Get-Date
Invoke-BenchClient "run" $Plan
$Seconds = ((Get-Date) - $StartTime).TotalSeconds
$Others = Get-Process | Where-Object { $_.Name -notin @("BenchServer", "BenchClient", "Idle") -and $null -ne $_.CPU } | ForEach-Object {
$Previous = 0
if ($Before.ContainsKey($_.Id)) { $Previous = $Before[$_.Id] }
[pscustomobject]@{ Name = $_.Name; Percent = 100 * ($_.CPU - $Previous) / $Seconds }
} | Sort-Object Percent -Descending | Select-Object -First 3
$Summary = Get-Content (Join-Path $RunDir "$Name.summary.json") -Raw | ConvertFrom-Json
$Summary | Add-Member -NotePropertyName OtherProcesses -NotePropertyValue (($Others | Where-Object Percent -ge 5 | ForEach-Object { "$($_.Name) $(Format-Num $_.Percent)" }) -join ", ")
$Summary | Add-Member -NotePropertyName Stage -NotePropertyValue $Name
$Summary | Add-Member -NotePropertyName Part -NotePropertyValue $Part
$Summary | Add-Member -NotePropertyName NodesPerServer -NotePropertyValue $Stage.Nodes
$script:Results += $Summary
# The query suite, on the idle servers.
Write-Plan $Plan $Servers $ClientKeys $Stage $Name (Join-Path $BenchDir "queries.txt") $false
Invoke-BenchClient "query" $Plan
$Rows = ($Summary.Servers | Measure-Object -Property Rows -Maximum).Maximum
foreach ($Query in (Get-Content (Join-Path $RunDir "$Name.queries.json") -Raw | ConvertFrom-Json)) {
$Query | Add-Member -NotePropertyName Stage -NotePropertyValue $Name
$Query | Add-Member -NotePropertyName DataRows -NotePropertyValue $Rows
$script:QueryResults += $Query
}
return $Summary
}
function Invoke-Seed($Servers, $TargetRows, $CurrentRows) {
$Nodes = $Servers.Count * $MaxNodesPerServer
$PerNode = [math]::Ceiling(($TargetRows - $CurrentRows) / $Nodes)
if ($PerNode -le 0) { return }
$Spec = ($Servers | ForEach-Object { "$($_.FirstNode)-$($_.FirstNode + $MaxNodesPerServer - 1)" }) -join ","
Write-Host ""
Write-Host "=== Seeding to ~$TargetRows rows per server ($PerNode more per node, in every database) ===" -ForegroundColor Cyan
Stop-Servers $Servers
$Dbs = $Servers | ForEach-Object { $_.DatabasePath }
& (Join-Path $OutDir "BenchSeed.exe") $TopicId $Spec $PerNode $MessageSize @Dbs | ForEach-Object { Write-Host " $_" }
if ($LASTEXITCODE -ne 0) { throw "BenchSeed failed" }
Start-Servers $Servers
}
# --- Report -----------------------------------------------------------------
function Format-Num($Value, $Decimals = 0) {
return ([double]$Value).ToString("N$Decimals", [Globalization.CultureInfo]::InvariantCulture)
}
function Get-Verdict($Summary) {
$Notes = @()
if ($Summary.Rate -gt 0 -and $Summary.PushRate -lt 0.9 * $Summary.OfferedRate) { $Notes += "push saturated" }
if ($Summary.Failed -gt 0) { $Notes += "$($Summary.Failed) failed pushes" }
# The trough slope is too noisy for a verdict (check-ins drift against the
# windows), the lag in seconds of pushes isn't: keeping up means about
# two check-ins' worth at most, through the hub.
$MaxLagSeconds = ($Summary.Servers | Measure-Object -Property LagMaxSeconds -Maximum).Maximum
if ($MaxLagSeconds -gt 2 * $PeerSyncInterval + 2) { $Notes += "replication lagging" }
if (-not $Summary.Drained) { $Notes += "NOT drained" }
elseif ($Summary.DrainSeconds -gt 2 * $PeerSyncInterval + 5) { $Notes += "slow drain" }
if ($Notes.Count -eq 0) { return "ok" }
return $Notes -join ", "
}
function Get-LogIssues($Servers) {
$Issues = @()
foreach ($Server in $Servers) {
$Logs = Get-ChildItem $LogDir -Filter "$($Server.Name)-*.log"
$Counts = [ordered]@{}
foreach ($Pattern in @("Refused", "Failed", "locked", "timed out", "Dropping", "Lost the link", "too big")) {
$Counts[$Pattern] = @($Logs | Select-String -SimpleMatch $Pattern).Count
}
$Sent = @($Logs | Select-String -Pattern "\[Peer\] Sent (\d+) messages .* in (\d+) ms")
$Messages = 0; $Ms = 0
foreach ($Match in $Sent) {
$Messages += [int]$Match.Matches[0].Groups[1].Value
$Ms += [int]$Match.Matches[0].Groups[2].Value
}
$Issues += [pscustomobject]@{
Server = $Server.Name; Counts = $Counts
ReplicatedOut = $Messages; ReplicateMs = $Ms; CatchUps = $Sent.Count
}
}
return $Issues
}
function Write-Report($Servers) {
$Lines = @()
$Lines += "# BakaShrot replication benchmark, $(Get-Date -Format 'yyyy-MM-dd HH:mm')"
$Lines += ""
$Cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name.Trim()
$Ram = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB)
$Lines += "- Machine: $Cpu, $Ram GB RAM, everything on localhost"
$Lines += "- Topology: $Topology, $ServerCount servers ($(($Servers | ForEach-Object { "$($_.Name) <-> " + (($_.Peers | ForEach-Object { $Servers[$_].Name }) -join '/') }) -join '; '))"
$Lines += "- Names: $Names ($(if ($Names -eq 'Wildcard') { 'each server names its own nodes, peers take them by AcceptNodes = n*' } else { 'every node named on every server' }))"
$Lines += "- Messages: ~$MessageSize bytes of JSON, PeerSyncInterval $PeerSyncInterval s, PeerBatchSize $PeerBatchSize, $PushSeconds s per stage"
$Lines += "- Built with: $($script:CompilerName), SQLite $((Get-Item (Join-Path $OutDir 'sqlite3.dll')).VersionInfo.ProductVersion)"
$Lines += "- CPU in % of one core (100 = one core busy), System = whole machine in %, Bench = the load generator itself (% of one core)"
$Lines += ""
$Lines += "## Stages"
$Lines += ""
$Lines += "- Max lag: most messages a server was missing while pushing. Trough: the lowest lag of the last check-in window, slope: how fast those troughs rise (~0 = keeps up)."
$Lines += ""
$Lines += "| Stage | Nodes | Offered msg/s | Pushed msg/s | Push p50 / p99 / max ms | Failed | Max lag msgs (s of pushes) | Last trough | Trough slope msg/s | Drain s | Verdict |"
$Lines += "|---|---|---|---|---|---|---|---|---|---|---|"
foreach ($R in $script:Results) {
$Offered = if ($R.Rate -gt 0) { Format-Num $R.OfferedRate } else { "max" }
$Lag = ($R.Servers | Measure-Object -Property LagMaxPush -Maximum).Maximum
$LagSeconds = ($R.Servers | Measure-Object -Property LagMaxSeconds -Maximum).Maximum
$Trough = ($R.Servers | Measure-Object -Property LagTroughLast -Maximum).Maximum
$Slope = ($R.Servers | Measure-Object -Property LagSlope -Maximum).Maximum
$Drain = if ($R.Drained) { Format-Num $R.DrainSeconds 1 } else { "> $DrainTimeout" }
$Lines += "| $($R.Stage) | $($R.NodesPerServer) x $ServerCount | $Offered | $(Format-Num $R.PushRate) | $(Format-Num $R.PushP50Ms 1) / $(Format-Num $R.PushP99Ms 1) / $(Format-Num $R.PushMaxMs 0) | $($R.Failed) | $(Format-Num $Lag) ($(Format-Num $LagSeconds 1)) | $(Format-Num $Trough) | $(Format-Num $Slope 1) | $Drain | $(Get-Verdict $R) |"
}
$Lines += ""
$Lines += "## Resources while pushing"
$Lines += ""
$Header = "| Stage | System CPU avg / max | Bench CPU |"
$Sep = "|---|---|---|"
foreach ($Server in $Servers) { $Header += " $($Server.Name) CPU avg / max | $($Server.Name) RAM WS / private MB |"; $Sep += "---|---|" }
$Header += " Other busy processes (% core) |"; $Sep += "---|"
$Lines += $Header
$Lines += $Sep
foreach ($R in $script:Results) {
$Row = "| $($R.Stage) | $(Format-Num $R.SystemCpuAvg) % / $(Format-Num $R.SystemCpuMax) % | $(Format-Num $R.BenchCpuAvg) |"
foreach ($S in $R.Servers) { $Row += " $(Format-Num $S.CpuAvgPush) / $(Format-Num $S.CpuMaxPush) | $(Format-Num $S.WorkingSetMaxMb 1) / $(Format-Num $S.PrivateMaxMb 1) |" }
$Row += " $($R.OtherProcesses) |"
$Lines += $Row
}
$Lines += ""
$Lines += "## Per server, end of stage"
$Lines += ""
$Header = "| Stage |"
$Sep = "|---|"
foreach ($Server in $Servers) { $Header += " $($Server.Name) rows | DB MB | max lag | monitor query avg / max ms |"; $Sep += "---|---|---|---|" }
$Lines += $Header
$Lines += $Sep
foreach ($R in $script:Results) {
$Row = "| $($R.Stage) |"
foreach ($S in $R.Servers) { $Row += " $(Format-Num $S.Rows) | $(Format-Num $S.DbMb 1) | $(Format-Num $S.LagMaxPush) | $(Format-Num $S.MonitorAvgMs 1) / $(Format-Num $S.MonitorMaxMs 1) |" }
$Lines += $Row
}
$Lines += ""
$Lines += "## Queries, idle, median ms (on $($Servers[0].Name))"
$Lines += ""
$Stages = $script:QueryResults | Where-Object Server -eq $Servers[0].Name | Select-Object -ExpandProperty Stage -Unique
$Names = $script:QueryResults | Select-Object -ExpandProperty Name -Unique
$Header = "| Query |"
$Sep = "|---|"
foreach ($Stage in $Stages) {
$Rows = ($script:QueryResults | Where-Object { $_.Stage -eq $Stage } | Select-Object -First 1).DataRows
$Header += " $Stage ($(Format-Num $Rows) rows) |"; $Sep += "---|"
}
$Lines += $Header
$Lines += $Sep
foreach ($Name in $Names) {
$Row = "| $Name |"
foreach ($Stage in $Stages) {
$Q = $script:QueryResults | Where-Object { $_.Stage -eq $Stage -and $_.Name -eq $Name -and $_.Server -eq $Servers[0].Name } | Select-Object -First 1
if (-not $Q) { $Row += " |" }
elseif ($Q.Count -eq 0) { $Row += " FAIL: $($Q.LastError) |" }
else { $Row += " $(Format-Num $Q.P50Ms 1) |" }
}
$Lines += $Row
}
$Lines += ""
$Mixed = $script:Results | Where-Object { $_.QueriesUnderLoad.Count -gt 0 }
foreach ($R in $Mixed) {
$Lines += "## Queries under load ($($R.Stage), on $($Servers[0].Name), while pushing $(Format-Num $R.PushRate) msg/s)"
$Lines += ""
$Lines += "| Query | Runs | p50 ms | p90 ms | max ms | Failures |"
$Lines += "|---|---|---|---|---|---|"
foreach ($Q in $R.QueriesUnderLoad) {
$Lines += "| $($Q.Name) | $($Q.Count) | $(Format-Num $Q.P50Ms 1) | $(Format-Num $Q.P90Ms 1) | $(Format-Num $Q.MaxMs 1) | $($Q.Failures) $($Q.LastError) |"
}
$Lines += ""
}
$Lines += "## Server logs"
$Lines += ""
$Lines += "| Server | Catch-ups sent | Messages replicated out | ms spent sending | Refused | Failed | locked | timed out | Dropping | Lost the link | too big |"
$Lines += "|---|---|---|---|---|---|---|---|---|---|---|"
foreach ($I in (Get-LogIssues $Servers)) {
$Lines += "| $($I.Server) | $($I.CatchUps) | $(Format-Num $I.ReplicatedOut) | $(Format-Num $I.ReplicateMs) | $(($I.Counts.Values) -join ' | ') |"
}
$Lines += ""
$Report = Join-Path $RunDir "report.md"
Set-Content -Path $Report -Value ($Lines -join "`r`n") -Encoding UTF8
@{ Results = $script:Results; Queries = $script:QueryResults } | ConvertTo-Json -Depth 8 | Set-Content (Join-Path $RunDir "results.json") -Encoding UTF8
return $Report
}
# --- Main -------------------------------------------------------------------
if (-not $SkipBuild) { Invoke-Build }
Copy-Dlls
New-Item -ItemType Directory -Force $RunDir, $LogDir | Out-Null
Write-Host "Run folder: $RunDir"
$ClientKeys = New-KeyPair
$Servers = @(New-Servers)
foreach ($Server in $Servers) { Write-ServerConfig $Server $Servers $ClientKeys }
try {
Start-Servers $Servers
$Last = $null
if ($PartList -contains "Ramp") {
$i = 0
foreach ($Spec in $Ramp.Split(",")) {
$i++
$Stage = ConvertTo-Stage $Spec
$Last = Invoke-Stage "Ramp" ("ramp{0:D2}-{1}" -f $i, $Spec.Trim()) $Stage $Servers $ClientKeys
}
}
if ($PartList -contains "Scale") {
foreach ($Target in $SeedTotals) {
$Current = 0
if ($Last) { $Current = ($Last.Servers | Measure-Object -Property Rows -Minimum).Minimum }
Invoke-Seed $Servers $Target $Current
$Last = Invoke-Stage "Scale" ("scale-{0}k" -f [math]::Round($Target / 1000)) (ConvertTo-Stage $SteadyStage) $Servers $ClientKeys
}
}
if ($PartList -contains "Mixed") {
$Last = Invoke-Stage "Mixed" "mixed" (ConvertTo-Stage $MixedStage) $Servers $ClientKeys -QueryLoad
}
}
finally {
Stop-Servers $Servers
if ($script:Results.Count -gt 0) {
$Report = Write-Report $Servers
Write-Host ""
Write-Host "Report: $Report"
}
Write-Host "Server logs: $LogDir"
if (-not $KeepData) {
Get-ChildItem $RunData -Filter "*.sqlite*" | Remove-Item -Force
} else {
Write-Host "Databases kept in $RunData"
}
}
File diff suppressed because it is too large Load Diff
+198
View File
@@ -0,0 +1,198 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BenchSeed.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Bench Seed
;
; Usage: BenchSeed <TopicId> <Nodes> <RowsPerNode> <MessageSize> <Db> [Db...]
; Nodes Node ids, "101-110,201-210".
;
; Adds RowsPerNode messages to every node, identical in every database, so
; servers that were in sync stay in sync without replicating anything: a
; quick way to get millions of rows for the query and check-in benchmarks.
; Each node continues from the highest message id any database has for it,
; and INSERT OR IGNORE keeps what's already there.
; Nodes go by name ("n" + id, like Bench-Replication.ps1 names them): each
; database stores a node under its own id for that name, and gets the name
; (origin "peer", as if a peer had sent it) if it doesn't have it yet, so
; servers that take nodes by wildcard (-Names Wildcard) see them as known.
; The servers must be stopped. Same JSON as BenchClient's pushes.
;
; Used by Tests/Bench/Bench-Replication.ps1, compile as a console program.
; ============================================================================
EnableExplicit
XIncludeFile "../../Server/Storage/Storage.pbi"
#Seed_BatchSize = 50000
; The id DbId has for node "n<Node>", given that name if it has none yet.
; Returns -1 on failure.
Procedure.i Seed_LocalNode(DbId.i, Node.i)
Protected Name.s = "n" + Str(Node), Id.i = -1
SetDatabaseString(DbId, 0, Name)
If DatabaseQuery(DbId, "SELECT node_id FROM nodes WHERE name = ?")
If NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
EndIf
If Id >= 0
ProcedureReturn Id
EndIf
; Its own id, unless something else is named there.
SetDatabaseLong(DbId, 0, Node)
SetDatabaseString(DbId, 1, Name)
If Not DatabaseUpdate(DbId, "INSERT INTO nodes (node_id, name, origin) VALUES (?, ?, 'peer') " +
"ON CONFLICT (node_id) DO UPDATE SET name = excluded.name, origin = 'peer' WHERE origin = 'id'")
ProcedureReturn -1
EndIf
SetDatabaseString(DbId, 0, Name)
If DatabaseQuery(DbId, "SELECT node_id FROM nodes WHERE name = ?")
If NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
EndIf
ProcedureReturn Id
EndProcedure
Procedure.s Seed_Json(NodeId.i, Seq.q, Pad.s)
Protected Kind.s, Value.i
If Seq % 50 = 0
Kind = "alert"
Else
Select Seq % 4
Case 0 : Kind = "temp"
Case 1 : Kind = "humidity"
Case 2 : Kind = "pressure"
Default : Kind = "status"
EndSelect
EndIf
Value = (Seq * 7919 + NodeId) % 10000
ProcedureReturn ~"{\"kind\":\"" + Kind + ~"\",\"node\":" + Str(NodeId) + ~",\"seq\":" + Str(Seq) +
~",\"value\":" + StrD(Value / 100.0, 2) + ~",\"ts\":" + Str(1700000000 + Seq) +
~",\"pad\":\"" + Pad + ~"\"}"
EndProcedure
Define TopicId.i, NodesSpec.s, RowsPerNode.i, MessageSize.i, Pad.s
Define NewList Nodes.i(), NewList Dbs.i()
Define i.i, Part.s, First.i, Last.i, Node.i, StartId.q, Id.q, MaxId.q, Count.q, StartMs.i, Total.q, d.i
Define Dim LocalIds.i(0)
OpenConsole()
If CountProgramParameters() < 5
PrintN("Usage: BenchSeed <TopicId> <Nodes> <RowsPerNode> <MessageSize> <Db> [Db...]")
End 1
EndIf
TopicId = Val(ProgramParameter(0))
NodesSpec = ProgramParameter(1)
RowsPerNode = Val(ProgramParameter(2))
MessageSize = Val(ProgramParameter(3))
If MessageSize > 90
Pad = LSet("", MessageSize - 90, "x")
EndIf
For i = 1 To CountString(NodesSpec, ",") + 1
Part = Trim(StringField(NodesSpec, i, ","))
If Part = ""
Continue
EndIf
If FindString(Part, "-")
First = Val(StringField(Part, 1, "-"))
Last = Val(StringField(Part, 2, "-"))
Else
First = Val(Part)
Last = First
EndIf
For Node = First To Last
AddElement(Nodes())
Nodes() = Node
Next
Next
For i = 4 To CountProgramParameters() - 1
AddElement(Dbs())
Dbs() = OpenStorageDatabase(ProgramParameter(i))
If Not Dbs() Or Not SetupStorageDatabase(Dbs())
PrintN("Can't open '" + ProgramParameter(i) + "': " + DatabaseError())
End 1
EndIf
Next
StartMs = ElapsedMilliseconds()
ReDim LocalIds(ListSize(Dbs()) - 1)
ForEach Nodes()
; Where every database is at for this node, continue after the furthest.
StartId = 0
d = 0
ForEach Dbs()
LocalIds(d) = Seed_LocalNode(Dbs(), Nodes())
If LocalIds(d) < 0
PrintN("Can't name node " + Str(Nodes()) + ": " + DatabaseError())
End 1
EndIf
MaxId = GetLatestMessageId(Dbs(), TopicId, LocalIds(d))
If MaxId > StartId
StartId = MaxId
EndIf
d + 1
Next
d = -1
ForEach Dbs()
d + 1
Id = StartId
While Id < StartId + RowsPerNode
If Not DatabaseUpdate(Dbs(), "BEGIN IMMEDIATE")
PrintN("BEGIN failed: " + DatabaseError())
End 1
EndIf
Count = 0
While Count < #Seed_BatchSize And Id < StartId + RowsPerNode
Id + 1
Count + 1
If Not InsertReplicatedMessage(Dbs(), TopicId, LocalIds(d), Id, Seed_Json(Nodes(), Id, Pad), BakaShrot_NowUtcMs())
PrintN("Insert failed: " + DatabaseError())
End 1
EndIf
Wend
If Not DatabaseUpdate(Dbs(), "COMMIT")
PrintN("COMMIT failed: " + DatabaseError())
End 1
EndIf
Total + Count
Wend
Next
Next
ForEach Dbs()
CloseDatabase(Dbs())
Next
PrintN("Seeded " + Str(Total) + " rows (" + Str(RowsPerNode) + " per node, " + Str(ListSize(Nodes())) + " nodes, " + Str(ListSize(Dbs())) + " databases) in " + StrD((ElapsedMilliseconds() - StartMs) / 1000.0, 1) + " s")
End 0
+75
View File
@@ -0,0 +1,75 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BenchServer.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Bench Server
;
; Usage: BenchServer <ConfigFile> <StopFile>
;
; The real server (Server/Root.pbi), without the console commands: it runs
; until StopFile exists, then stops its workers cleanly and exits.
; BakaShrot_Server.exe can't run headless, with no console input its
; Input() returns Chr(4) and it stops right away, see Notes.md.
;
; Used by Tests/Bench/Bench-Replication.ps1, compile as a thread-safe console
; program.
; ============================================================================
EnableExplicit
XIncludeFile "../../Server/Root.pbi"
Define Root.BakaShrot_Root
Define StopFile.s
OpenConsole("BakaShrot Bench Server")
If CountProgramParameters() < 2
PrintN("Usage: BenchServer <ConfigFile> <StopFile>")
End 1
EndIf
Root\ConfigPath = ProgramParameter(0)
StopFile = ProgramParameter(1)
If Not BakaShrot_Root_LoadConfig(@Root)
End 1
EndIf
If Not BakaShrot_Root_OpenDatabase(@Root)
FreeConfig(Root\Config)
End 1
EndIf
If Not BakaShrot_Root_StartWorkers(@Root)
BakaShrot_Root_CloseDatabase(@Root)
FreeConfig(Root\Config)
End 1
EndIf
PrintN("Running until '" + StopFile + "' exists.")
While FileSize(StopFile) < 0
Delay(200)
Wend
PrintN("Stopping...")
BakaShrot_Root_StopWorkers(@Root)
BakaShrot_Root_CloseDatabase(@Root)
FreeConfig(Root\Config)
End 0
+106
View File
@@ -0,0 +1,106 @@
# ============================================================================
# Compares runs of Bench-Replication.ps1 side by side, as a markdown table.
#
# Usage:
# powershell -ExecutionPolicy Bypass -File Tests\Bench\Compare-Runs.ps1 `
# -Runs "Build\Bench\runs\20261107-123413,Build\Bench\runs\20261107-125334" `
# -Labels "Before,WAL + wake-ups" [-Out comparison.md]
#
# Picks the key numbers of each run's results.json: the push ceilings, the
# latencies, replication lag and drain, CPU and RAM, the queries at the
# biggest data size, and the mixed stage. Stages missing from a run show "-".
# ============================================================================
param(
[Parameter(Mandatory = $true)] [string[]]$Runs,
[string[]]$Labels = @(),
[string]$Out = ""
)
$ErrorActionPreference = "Stop"
# "powershell -File" passes "a,b" as one string.
$Runs = @($Runs | ForEach-Object { $_ -split "," } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
$Labels = @($Labels | ForEach-Object { $_ -split "," } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
$Culture = [Globalization.CultureInfo]::InvariantCulture
function Format-Num($Value, $Decimals = 0) {
if ($null -eq $Value) { return "-" }
return ([double]$Value).ToString("N$Decimals", $Culture)
}
$Data = @()
for ($i = 0; $i -lt $Runs.Count; $i++) {
$Json = Get-Content (Join-Path $Runs[$i] "results.json") -Raw | ConvertFrom-Json
$Label = if ($i -lt $Labels.Count) { $Labels[$i] } else { Split-Path $Runs[$i] -Leaf }
$Data += [pscustomobject]@{ Label = $Label; Results = @($Json.Results); Queries = @($Json.Queries) }
}
# A stage by the end of its name ("5x0" matches "ramp05-5x0").
function Get-Stage($Run, $Suffix) {
return $Run.Results | Where-Object { $_.Stage -like "*$Suffix" } | Select-Object -First 1
}
function Get-Max($Stage, $Property) {
if (-not $Stage) { return $null }
return ($Stage.Servers | Measure-Object -Property $Property -Maximum).Maximum
}
function Get-Avg($Stage, $Property) {
if (-not $Stage) { return $null }
return ($Stage.Servers | Measure-Object -Property $Property -Average).Average
}
# Median of a query on the first server, in the last stage that ran it.
function Get-Query($Run, $Name) {
$Q = $Run.Queries | Where-Object { $_.Name -eq $Name -and $_.Server -eq $Run.Results[0].Servers[0].Name } | Select-Object -Last 1
if (-not $Q -or $Q.Count -eq 0) { return $null }
return $Q.P50Ms
}
function Get-LoadQuery($Run, $Name) {
$Mixed = Get-Stage $Run "mixed"
if (-not $Mixed) { return $null }
$Q = $Mixed.QueriesUnderLoad | Where-Object Name -eq $Name | Select-Object -First 1
if (-not $Q) { return $null }
return $Q.P50Ms
}
$Rows = @(
@("**Push ceiling**, msg/s, 5 nodes/server", { param($R) Format-Num (Get-Stage $R "5x0").PushRate }),
@("**Push ceiling**, msg/s, 10 nodes/server", { param($R) Format-Num (Get-Stage $R "10x0").PushRate }),
@("Pushed of 2,000 offered (10 x 50)", { param($R) Format-Num (Get-Stage $R "10x50").PushRate }),
@("Pushed of 4,000 offered (10 x 100)", { param($R) Format-Num (Get-Stage $R "10x100").PushRate }),
@("Push p50 / p99 ms, 10 x 50", { param($R) $S = Get-Stage $R "10x50"; if ($S) { "$(Format-Num $S.PushP50Ms 1) / $(Format-Num $S.PushP99Ms 1)" } else { "-" } }),
@("Push p50 / p99 / max ms, flat out (10 nodes)", { param($R) $S = Get-Stage $R "10x0"; if ($S) { "$(Format-Num $S.PushP50Ms 1) / $(Format-Num $S.PushP99Ms 1) / $(Format-Num $S.PushMaxMs)" } else { "-" } }),
@("Replication lag, s of pushes, flat out", { param($R) Format-Num (Get-Max (Get-Stage $R "10x0") "LagMaxSeconds") 1 }),
@("Drain after the push, s, flat out", { param($R) Format-Num (Get-Stage $R "10x0").DrainSeconds 1 }),
@("Server CPU, % of a core, flat out (avg of the 4)", { param($R) Format-Num (Get-Avg (Get-Stage $R "10x0") "CpuAvgPush") }),
@("Machine CPU %, flat out", { param($R) Format-Num (Get-Stage $R "10x0").SystemCpuAvg }),
@("Hub RAM, working set MB, max", { param($R) Format-Num (($R.Results | ForEach-Object { $_.Servers[0].WorkingSetMaxMb } | Measure-Object -Maximum).Maximum) 1 }),
@("Rows per server at the end", { param($R) Format-Num $R.Results[-1].Servers[0].Rows }),
@("Query: latest message, ms (1M rows)", { param($R) Format-Num (Get-Query $R "latest_message") 1 }),
@("Query: last 50 of a node, ms", { param($R) Format-Num (Get-Query $R "last_50_of_node") 1 }),
@("Query: sync state (GROUP BY all), ms", { param($R) Format-Num (Get-Query $R "sync_state") 1 }),
@("Query: sync state from node_heads (what check-ins use now), ms", { param($R) Format-Num (Get-Query $R "sync_state_heads") 1 }),
@("Query: JSON count over all rows, ms", { param($R) Format-Num (Get-Query $R "json_count_all") 1 }),
@("Query: JSON aggregate over all rows, ms", { param($R) Format-Num (Get-Query $R "json_agg_all") 1 }),
@("**Mixed:** pushed of 400 msg/s with a query loop", { param($R) Format-Num (Get-Stage $R "mixed").PushRate }),
@("Mixed: push p99 / max ms", { param($R) $S = Get-Stage $R "mixed"; if ($S) { "$(Format-Num $S.PushP99Ms 1) / $(Format-Num $S.PushMaxMs)" } else { "-" } }),
@("Mixed: failed pushes", { param($R) $S = Get-Stage $R "mixed"; if ($S) { $S.Failed } else { "-" } }),
@("Mixed: JSON count over all rows, ms, under load", { param($R) Format-Num (Get-LoadQuery $R "json_count_all") 1 }),
@("Mixed: latest message, ms, under load", { param($R) Format-Num (Get-LoadQuery $R "latest_message") 1 })
)
$Lines = @()
$Lines += "| | " + (($Data | ForEach-Object { $_.Label }) -join " | ") + " |"
$Lines += "|---|" + (($Data | ForEach-Object { "---" }) -join "|") + "|"
foreach ($Row in $Rows) {
$Cells = foreach ($Run in $Data) { & $Row[1] $Run }
$Lines += "| $($Row[0]) | " + ($Cells -join " | ") + " |"
}
$Text = $Lines -join "`r`n"
if ($Out) { Set-Content -Path $Out -Value $Text -Encoding UTF8 }
$Text
+182
View File
@@ -0,0 +1,182 @@
# Benchmark results, 2026-11-07
`Bench-Replication.ps1` with its defaults: 4 servers in a Y (a hub linked to
3 leaves), 5-10 nodes pushing to each, ~200-byte JSON messages, 30 s per
stage, `PeerSyncInterval = 5`, `PeerBatchSize = 100`. All on one machine
(i5-13500, 16 GB, NVMe), PureBasic 5.73 x64 unless said otherwise, SQLite
3.54.1. Table made with `Compare-Runs.ps1`.
| Version | What changed |
|---|---|
| Before | Rollback journal, a sync to disk per push, every wait a `Delay(5)` / `Delay(1)` loop |
| WAL + wake-ups | WAL with `synchronous = NORMAL`, threads woken by an event / `select()`, a write mutex instead of SQLite's busy-wait |
| + grouping | Pushes arriving together share one transaction (group commit) |
| + no per-push log | The `PrintN()` per push / read / query removed (`#BakaShrot_Net_LogRequests`) |
| + prepared/cache/checkpoints/heads | One writer connection with prepared statements (SQLite's own API), next ids cached in memory, WAL checkpoints in a background thread, the sync state from `node_heads` (`Server/Storage/Writer.pbi`) |
| same on PB 6.40 C | The same code, built with PureBasic 6.40's C backend and `/OPTIMIZER` (the load generator too) |
| | Before | WAL + wake-ups | + grouping | + no per-push log | + prepared/cache/checkpoints/heads (5.73) | same on PB 6.40 C |
|---|---|---|---|---|---|---|
| **Push ceiling**, msg/s, 5 nodes/server | 958 | 5,771 | 5,709 | 25,681 | 33,522 | 37,162 |
| **Push ceiling**, msg/s, 10 nodes/server | 904 | 5,726 | 5,814 | 25,707 | 34,345 | 38,358 |
| Pushed of 2,000 offered (10 x 50) | 924 | 1,999 | 2,000 | 2,000 | 2,000 | 1,999 |
| Pushed of 4,000 offered (10 x 100) | 899 | 4,000 | 4,000 | 4,000 | 4,000 | 4,000 |
| Push p50 / p99 ms, 10 x 50 | 18.0 / 491.5 | 0.4 / 5.1 | 0.5 / 7.2 | 0.5 / 13.6 | 0.3 / 0.8 | 0.2 / 0.9 |
| Push p50 / p99 / max ms, flat out (10 nodes) | 18.0 / 574.9 / 2,642 | 5.5 / 25.2 / 193 | 5.6 / 23.1 / 56 | 0.9 / 16.5 / 149 | 0.5 / 2.8 / 854 | 0.5 / 2.5 / 1,485 |
| Replication lag, s of pushes, flat out | 8.9 | 5.1 | 5.0 | 8.9 | 9.9 | 8.3 |
| Drain after the push, s, flat out | 6.2 | 5.8 | 5.8 | 10.3 | 11.3 | 11.3 |
| Server CPU, % of a core, flat out (avg of the 4) | 45 | 65 | 66 | 130 | 120 | 121 |
| Machine CPU %, flat out | 41 | 33 | 34 | 67 | 65 | 65 |
| Hub RAM, working set MB, max | 34.6 | 42.9 | 44.6 | 45.2 | 38.8 | 40.1 |
| Rows per server at the end | 1,021,883 | 1,024,025 | 1,024,025 | 1,887,117 | 2,389,201 | 2,619,806 |
| Query: latest message, ms (1M rows) | 5.9 | 0.5 | 0.5 | 0.1 | 0.1 | 0.1 |
| Query: last 50 of a node, ms | 5.8 | 1.0 | 1.0 | 0.7 | 0.8 | 0.7 |
| Query: sync state (GROUP BY all), ms | 78.0 | 73.1 | 72.1 | 131.9 | 166.7 | 184.1 |
| Query: sync state from node_heads (what check-ins use now), ms | - | - | - | - | 0.6 | 0.5 |
| Query: JSON count over all rows, ms | 473.6 | 475.1 | 475.3 | 857.5 | 1,080.7 | 1,199.4 |
| Query: JSON aggregate over all rows, ms | 1,647.8 | 1,575.8 | 1,533.9 | 2,800.2 | 3,974.2 | 4,371.2 |
| **Mixed:** pushed of 400 msg/s with a query loop | 323 | 396 | 397 | 397 | 392 | 396 |
| Mixed: push p99 / max ms | 820.2 / 5,119 | 0.7 / 17 | 7.9 / 17 | 18.0 / 30 | 1.2 / 17 | 0.9 / 17 |
| Mixed: failed pushes | 1 | 0 | 0 | 0 | 0 | 0 |
| Mixed: JSON count over all rows, ms, under load | 545.4 | 502.3 | 506.5 | 925.0 | 1,148.2 | 1,265.6 |
| Mixed: latest message, ms, under load | 12.0 | 0.2 | 0.2 | 0.1 | 0.2 | 0.2 |
The full-table scans grow with the data, and the later runs' flat-out stages
wrote more of it: 1.9M, 2.4M, then 2.6M rows per server instead of ~1.02M.
Per row they cost the same (~0.45 ms per 1,000 rows for the JSON count).
PB 6.40 doesn't change them either, SQLite does the scanning.
## What limited each version
- **Before:** the sync to disk on every push, ~250 commits/s per database.
- **WAL + wake-ups:** not the database anymore. The `PrintN()` logging every
push takes ~0.4 ms and serializes every thread behind it: ~2,400 pushes/s
per server whatever the number of nodes, with the server mostly idle
(measured on a single server: the listener asleep in `select()` 91 % of
the time, the writes busy 33 %, 0.14 ms per push).
- **+ grouping:** same cap, so no gain yet: the pushes never piled up
behind the write mutex (1.0 per transaction on average). It did cut the
worst push from 193 to 56 ms.
- **+ no per-push log:** a single server went from ~2,400 to ~12,000
pushes/s, and grouping now kicks in: 2.5 pushes per transaction at 5
nodes, ~5-9 at 10-20, the database busy 70-90 % of the time at 0.07-0.11
ms per push. The cluster tops out at ~25,700 msg/s with the machine at
67 % CPU (the load generator itself ~85 % of a core). Next limits: each
server's write section, and running everything on one machine.
- **+ prepared/cache/checkpoints/heads:** ~25,700 -> ~34,300 msg/s. A push
costs ~0.05 ms of write time instead of 0.07-0.11, no statement is
prepared again, no MAX() per push. The p99 at moderate load is back under
1 ms (13.6 -> 0.8 ms at 10 x 50, 18 -> 1.2 ms in the mixed stage): the
checkpoints were what held the writes up. Flat out, the WAL grows faster
than the background checkpoints keep up with, so the writer checkpoints by
itself past 10,000 frames, and the worst push goes from 149 to 854 ms. The
sync state every check-in reads: 0.5 ms instead of a 167 ms GROUP BY.
- **Same on PB 6.40 C:** ~34,300 -> ~38,400 msg/s (+12 %), the same
latencies, slightly less lag. Both the servers and the load generator are
built with it, so part of it may be the generator. The SQLite side (the
write section, the queries) is the same DLL either way.
## Notes
- Ids checked after the last four runs: every node 1..N, no gap, no
duplicate, on all 4 servers, and `node_heads` exactly matching `data`.
- **p99 at moderate load went up with grouping** (0.7 -> 8-18 ms), and came
back down once the checkpoints left the write path (see above).
- Replication keeps up at every load: it drains within ~11 s even after
38,000 msg/s. The lag is the check-in wait (`PeerSyncInterval`) plus the
hub relaying to its leaves, see `Design/Suggestions.md` #2 to lower it.
- The worst push flat out (0.85-1.5 s) is the writer's backstop checkpoint,
see `Design/Suggestions.md` #3.
## Names and wildcards (evening)
Same benchmark, PureBasic 5.73, after topics and nodes got names, strict
"named on both sides" replication, and wildcards, run with `-Names
Wildcard`: each server only names its own nodes, and takes everyone else's
by `AcceptNodes = n*`, so each server adds the other servers' 30 nodes
under ids of its own (counting down from 65535), and the hub relays them on
by name. The worst case for the new code: every batch goes through a name
lookup and every check-in through the patterns. Run `20261107-220433`,
compared with `Compare-Runs.ps1` (`comparison.md` in the run's folder).
| | Before names (5.73) | Before names (PB 6.40 C) | Names + wildcards (5.73) |
|---|---|---|---|
| **Push ceiling**, msg/s, 5 nodes/server | 33,522 | 37,162 | 35,124 |
| **Push ceiling**, msg/s, 10 nodes/server | 34,345 | 38,358 | 32,846 |
| Push p50 / p99 ms, 10 x 50 | 0.3 / 0.8 | 0.2 / 0.9 | 0.3 / 1.1 |
| Push p50 / p99 / max ms, flat out (10 nodes) | 0.5 / 2.8 / 854 | 0.5 / 2.5 / 1,485 | 0.6 / 3.2 / 1,503 |
| Replication lag, s of pushes, flat out | 9.9 | 8.3 | 8.6 |
| Drain after the push, s, flat out | 11.3 | 11.3 | 11.8 |
| Server CPU, % of a core, flat out (avg of the 4) | 120 | 121 | 129 |
| Hub RAM, working set MB, max | 38.8 | 40.1 | 39.3 |
| Rows per server at the end | 2,389,201 | 2,619,806 | 2,395,509 |
| Query: sync state from node_heads, ms | 0.6 | 0.5 | 0.7 |
| Query: JSON count over all rows, ms | 1,080.7 | 1,199.4 | 1,105.8 |
| **Mixed:** pushed of 400 msg/s with a query loop | 392 | 396 | 397 |
| Mixed: push p99 / max ms | 1.2 / 17 | 0.9 / 17 | 0.9 / 18 |
| Failed pushes, refusals between servers | 0 | 0 | 0 |
- **Same speed, within run-to-run noise.** Flat out at 10 nodes, the same
build gave 32,976 and 37,003 msg/s in two ramp-only runs (declared names)
earlier this evening: ±6 % between runs is usual on this machine. The push
path itself didn't change, only the check-ins and the batches' first
lines.
- **Server CPU +7 %** flat out (129 vs 120 % of a core), the name lookups
and the bigger sync states, possibly part of the noise too.
- **Replication** keeps up at every load and drains in the same time; no
batch refused anywhere, every server ended with the same rows.
- **Measuring changed slightly:** the lag monitor now asks for each node's
latest id by name through the `messages` view (ids differ between
servers in this mode), the old runs asked `data` by id. Both are index
lookups.
## Big messages, no JSON check on push, is_json clause (2026-11-08)
Same setup as the evening run (`-Names Wildcard`), after: packets up to
16 MB once authenticated (new inbox: growth by doubling, a read offset),
replication batches still ~64 KB, pushes no longer checked to be JSON
(`ParseJSON()` gone from the push path, `is_json` flags them), and
`is_json = 1` added to the JSON queries.
| | Before names (5.73) | Before names (PB 6.40 C) | Names + wildcards (5.73) | Big messages, no JSON check, is_json clause (5.73) |
|---|---|---|---|---|
| **Push ceiling**, msg/s, 5 nodes/server | 33,522 | 37,162 | 35,124 | **38,199** |
| **Push ceiling**, msg/s, 10 nodes/server | 34,345 | 38,358 | 32,846 | **37,745** |
| Pushed of 2,000 offered (10 x 50) | 2,000 | 1,999 | 1,999 | 2,001 |
| Pushed of 4,000 offered (10 x 100) | 4,000 | 4,000 | 4,000 | 4,000 |
| Push p50 / p99 ms, 10 x 50 | 0.3 / 0.8 | 0.2 / 0.9 | 0.3 / 1.1 | 0.3 / 1.0 |
| Push p50 / p99 / max ms, flat out (10 nodes) | 0.5 / 2.8 / 854 | 0.5 / 2.5 / 1,485 | 0.6 / 3.2 / 1,503 | 0.5 / 2.9 / 822 |
| Replication lag, s of pushes, flat out | 9.9 | 8.3 | 8.6 | 10.5 |
| Drain after the push, s, flat out | 11.3 | 11.3 | 11.8 | 13.8 |
| Server CPU, % of a core, flat out (avg of the 4) | 120 | 121 | 129 | 120 |
| Machine CPU %, flat out | 65 | 65 | 69 | 66 |
| Hub RAM, working set MB, max | 38.8 | 40.1 | 39.3 | 42.8 |
| Rows per server at the end | 2,389,201 | 2,619,806 | 2,395,509 | 2,628,001 |
| Query: latest message, ms | 0.1 | 0.1 | 0.1 | 0.1 |
| Query: last 50 of a node, ms | 0.8 | 0.7 | 0.8 | 0.8 |
| Query: sync state (GROUP BY all), ms | 166.7 | 184.1 | 170.5 | 187.9 |
| Query: sync state from node_heads (what check-ins use now), ms | 0.6 | 0.5 | 0.7 | 0.6 |
| Query: JSON count over all rows, ms | 1,080.7 | 1,199.4 | 1,105.8 | 1,233.6 |
| Query: JSON aggregate over all rows, ms | 3,974.2 | 4,371.2 | 4,084.2 | 4,464.4 |
| Same, per million rows: sync state / JSON count / JSON aggregate, ms | 69.8 / 452 / 1,663 | 70.3 / 458 / 1,669 | 71.2 / 462 / 1,705 | 71.5 / 469 / 1,699 |
| **Mixed:** pushed of 400 msg/s with a query loop | 392 | 396 | 397 | 384 |
| Mixed: push p99 / max ms | 1.2 / 17 | 0.9 / 17 | 0.9 / 18 | 1.0 / 15 |
| Mixed: failed pushes | 0 | 0 | 0 | 0 |
| Mixed: JSON count over all rows, ms, under load | 1,148.2 | 1,265.6 | 1,179.5 | 1,313.4 |
| Mixed: latest message, ms, under load | 0.2 | 0.2 | 0.2 | 0.2 |
Runs: `20261107-140556`, `20261107-141735`, `20261107-220433`, `20261108-033149` (all 4 servers in a Y, ~200-byte messages; the last two with `-Names Wildcard`). Query times are from the end of each run, so they scale with its row count: compare the per-million row.
- **Push ceiling up 9-15 %** (38,199 / 37,745 msg/s), the best yet on 5.73,
for the same server CPU (120 % of a core). Likely mostly `ParseJSON()`
leaving the push path, though runs of one build have spread 33-37k.
- **Lag and drain** are a bit higher in seconds, with 15 % more messages
pushed per second to relay (397,066 messages behind at most, vs 282,621).
- **The `is_json = 1` clause costs nothing measurable:** per million rows,
the JSON count is 469 ms vs 462, the aggregate 1,699 vs 1,705.
- **Mixed: 384 of 400 msg/s pushed** (397 before), with no failures and a
lower p99. The bench's pushers are paced by its own loop, and this run's
database was 10 % bigger, so the query loop beside them was slower. Worth
a second run before reading anything into it.
- 0 refused, failed or "too big" in the server logs, 2,628,001 rows on all
4 servers.
+30
View File
@@ -0,0 +1,30 @@
# Query suite, run by BenchClient's "query" mode after every stage, see
# Bench-Replication.ps1. One per line: Name | SQL
# {TOPIC} and {NODE} are replaced by the topic id and the server's first node.
# "@latest" is a GetLatestMessage of {NODE}, the regular read path.
# Results must fit in one packet (64 KB) and 10000 rows.
#
# The messages look like:
# {"kind":"temp","node":101,"seq":12,"value":42.17,"ts":1700000012,"pad":"xxx"}
# kind is "alert" for 1 in 50, the others are spread evenly.
# Indexed, should stay flat as the data grows.
latest_message | @latest
last_50_of_node | SELECT message_id, message_data FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} ORDER BY message_id DESC LIMIT 50
max_of_node | SELECT MAX(message_id) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE}
by_message_id | SELECT topic_id, node_id FROM data WHERE message_id = 100
recent_global | SELECT topic_id, node_id, message_id FROM data ORDER BY rowid DESC LIMIT 100
# Bounded JSON scan: newest alerts of one node, about 50 rows read per hit.
json_alerts_node | SELECT message_id, message_data ->> '$.value' FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} AND is_json = 1 AND message_data ->> '$.kind' = 'alert' ORDER BY message_id DESC LIMIT 100
# Index scans, grow with the data.
count_node | SELECT COUNT(*) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE}
count_all | SELECT COUNT(*) FROM data
sync_state | SELECT topic_id, node_id, MAX(message_id) FROM data GROUP BY topic_id, node_id ORDER BY topic_id, node_id
sync_state_heads | SELECT topic_id, node_id, max_message_id FROM node_heads ORDER BY topic_id, node_id
# Full table scans parsing every message's JSON, the ones that die first.
json_count_all | SELECT COUNT(*) FROM data WHERE is_json = 1 AND message_data ->> '$.kind' = 'alert'
json_agg_all | SELECT message_data ->> '$.kind', COUNT(*), ROUND(AVG(message_data ->> '$.value'), 2) FROM data WHERE is_json = 1 GROUP BY 1
json_agg_node | SELECT message_data ->> '$.kind', COUNT(*), ROUND(AVG(message_data ->> '$.value'), 2) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} AND is_json = 1 GROUP BY 1
+13
View File
@@ -0,0 +1,13 @@
# Queries run in a loop while pushing, in the "mixed" stage of
# Bench-Replication.ps1, to see how reads hold up under write load, and how
# much a long read slows the writes down (it used to block every commit,
# before WAL).
# Same format as queries.txt.
latest_message | @latest
last_50_of_node | SELECT message_id, message_data FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} ORDER BY message_id DESC LIMIT 50
json_alerts_node | SELECT message_id, message_data ->> '$.value' FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} AND is_json = 1 AND message_data ->> '$.kind' = 'alert' ORDER BY message_id DESC LIMIT 100
count_node | SELECT COUNT(*) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE}
sync_state | SELECT topic_id, node_id, MAX(message_id) FROM data GROUP BY topic_id, node_id ORDER BY topic_id, node_id
sync_state_heads | SELECT topic_id, node_id, max_message_id FROM node_heads ORDER BY topic_id, node_id
json_count_all | SELECT COUNT(*) FROM data WHERE is_json = 1 AND message_data ->> '$.kind' = 'alert'
+346
View File
@@ -0,0 +1,346 @@
# End-to-end test of big messages: up to 16 MB once authenticated, 4 KB
# frames before that (Commons/Networking/Connections.pbi).
# Two linked servers: pushes of 100 KB, 1 MB and just under the cap, read
# back through the client DLL, replicated to the other server, small ones
# still batched, a push over the cap refused, and frames too big for the
# handshake cutting the connection right away.
# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe (Bench-Replication.ps1,
# or compile Tests\Bench\BenchServer.pb into it). Uses ports 12403-12404.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\BigMessages-Test.ps1
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"))
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_bigtest"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Fails = 0
# Same as Packets.pbi.
$MaxPacketSize = 16 * 1024 * 1024
$MaxMessageSize = $MaxPacketSize - 4096
function New-KeyPair {
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
$C = New-Object System.Net.Sockets.TcpClient
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
}
function Tool([string]$Name, [string[]]$A) {
$O = & (Join-Path $Build $Name) @A 2>&1
@{ Code = $LASTEXITCODE; Out = ($O -join " | ") }
}
function Check([string]$What, [bool]$Ok, [string]$Detail) {
if (-not $Ok) { $script:Fails++ }
"{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail
}
function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) {
$Out = $Result.Out
if ($Out.Length -gt 300) { $Out = $Out.Substring(0, 300) + "... (" + $Result.Out.Length + " chars)" }
Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Out)
}
function Start-Srv($Name) {
$Stop = Join-Path $Dir "$Name.stop"
Remove-Item $Stop -ErrorAction SilentlyContinue
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput (Join-Path $Dir "$Name.log") -WindowStyle Hidden -PassThru
$null = $P.Handle
@{ P = $P; Stop = $Stop; Name = $Name }
}
function Stop-Srv($S) {
Set-Content $S.Stop "x"
if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force }
}
function Wait-Port($Port, $S) {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content (Join-Path $Dir "$($S.Name).log") -Raw)" }
if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" }
Start-Sleep -Milliseconds 100
}
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
}
# Waits until Sql answers something matching Pattern, for up to Seconds.
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 30) {
$D = (Get-Date).AddSeconds($Seconds)
do {
$R = Query $Sql $Ini
if ($R.Code -eq 0 -and $R.Out -match $Pattern) { return $R }
Start-Sleep -Milliseconds 250
} while ((Get-Date) -lt $D)
$R
}
# A JSON message of exactly Size bytes, in a file, as BakaShrotPushMessage's @File.
function New-Message($Name, [int]$Size) {
$P = Join-Path $Dir "$Name.json"
$Head = '{"n":"' + $Name + '","pad":"'
$Tail = '"}'
$Pad = $Size - $Head.Length - $Tail.Length
$B = New-Object System.Text.StringBuilder ($Size)
[void]$B.Append($Head)
[void]$B.Append(("0123456789abcdef" * [math]::Ceiling($Pad / 16)).Substring(0, $Pad))
[void]$B.Append($Tail)
[IO.File]::WriteAllText($P, $B.ToString(), (New-Object System.Text.UTF8Encoding $false))
"@$P"
}
# Connects, sends one frame header announcing Size bytes, then up to 64 KB of
# zeros, and tells whether the server closed (or reset) the connection
# within 3 s, rather than waiting for the rest.
function Test-RawFrame([int]$Port, [int]$Size) {
$C = New-Object System.Net.Sockets.TcpClient
$Start = Get-Date
try {
$C.Connect("127.0.0.1", $Port)
$S = $C.GetStream()
$S.ReadTimeout = 5000
$S.Write([BitConverter]::GetBytes([int]$Size), 0, 4)
try { $S.Write((New-Object byte[] ([math]::Min($Size, 65536))), 0, [math]::Min($Size, 65536)) } catch { }
$Buffer = New-Object byte[] 16
try { $Read = $S.Read($Buffer, 0, 16) } catch { $Read = -1 }
($Read -le 0) -and (((Get-Date) - $Start).TotalSeconds -lt 3)
} catch { ((Get-Date) - $Start).TotalSeconds -lt 3 } finally { $C.Close() }
}
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair
# Same names on both, different ids.
Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($A.Priv)
Node = serverA
[BakaShrot.Topics]
logs = 1
[BakaShrot.Nodes]
serverA = 10
serverB = 11
kitchen = 2
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12403
ReplicatingTopics = logs
DatabasePath = $(Join-Path $Dir "a.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
[BakaShrot.Peer.b]
Host = 127.0.0.1
Port = 12404
Node = serverB
PublicKey = $($B.Pub)
[BakaShrot.Client.b]
PublicKeys = $($B.Pub)
Node = serverB
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Node = kitchen
DefaultTopic = logs
ReadTopics = *
AllowQuery = 1
"@
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($B.Priv)
Node = serverB
[BakaShrot.Topics]
logs = 300
[BakaShrot.Nodes]
serverA = 1
serverB = 2
kitchen = 30
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12404
ReplicatingTopics = logs
DatabasePath = $(Join-Path $Dir "b.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
[BakaShrot.Peer.a]
Host = 127.0.0.1
Port = 12403
Node = serverA
PublicKey = $($A.Pub)
[BakaShrot.Client.a]
PublicKeys = $($A.Pub)
Node = serverA
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Node = kitchen
DefaultTopic = logs
ReadTopics = *
AllowQuery = 1
"@
$ServerKeys = @{ 12403 = $A.Pub; 12404 = $B.Pub }
function Client-Ini($Name, $Port) {
$P = Join-Path $Dir "$Name.ini"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
$P
}
$OnA = Client-Ini "kitchen-a" 12403
$OnB = Client-Ini "kitchen-b" 12404
$Sizes = [ordered]@{ "m100k" = 100 * 1024; "m1m" = 1024 * 1024; "mmax" = $MaxMessageSize }
$Files = @{}
foreach ($N in $Sizes.Keys) { $Files[$N] = New-Message $N $Sizes[$N] }
$Over = New-Message "over" ($MaxMessageSize + 1)
# Not JSON: 1 MB of it cut short, and plain text. Stored anyway, is_json = 0.
$Broken = Join-Path $Dir "broken.json"
[IO.File]::WriteAllText($Broken, ([IO.File]::ReadAllText($Files["m1m"].Substring(1))).Substring(0, 1000000))
$Text = Join-Path $Dir "text.txt"
[IO.File]::WriteAllText($Text, "just some text, not JSON")
$Small = New-Message "small" 40
$SA = Start-Srv "a"; $SB = Start-Srv "b"
try {
Wait-Port 12403 $SA; Wait-Port 12404 $SB
"--- Before authenticating"
Check "a frame over 4 KB is cut right away" (Test-RawFrame 12403 4097) "connection closed"
Check "a 16 MB frame too" (Test-RawFrame 12403 $MaxPacketSize) "connection closed"
Check "the server still serves after that" (Test-Port 12403) "listening"
"--- Pushes"
$Id = 0
foreach ($N in $Sizes.Keys) {
$Id++
$T = Measure-Command { $R = Tool "BakaShrotPushMessage.exe" @($Files[$N], $OnA) }
Expect ("push of {0:N0} bytes ({1:N0} ms)" -f $Sizes[$N], $T.TotalMilliseconds) $R "message #$Id"
}
Expect "a push 1 byte over the cap is refused" (Tool "BakaShrotPushMessage.exe" @($Over, $OnA)) "too big" 1
$Id++
Expect "a small push after them" (Tool "BakaShrotPushMessage.exe" @($Small, $OnA)) "message #$Id"
"--- Read back"
$T = Measure-Command { $O = & (Join-Path $Build "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnA 2>&1 }
$Code = $LASTEXITCODE
Check "latest is the small one" ($Code -eq 0 -and ($O -join "") -match '"n":"small"') ($O -join " | ")
$R = Query "SELECT message_id, length(message_data) FROM data WHERE node_id = 2 ORDER BY message_id" $OnA
Expect "stored sizes on A" $R ('\[\["1","{0}"\],\["2","{1}"\],\["3","{2}"\],\["4","40"\]\]' -f $Sizes["m100k"], $Sizes["m1m"], $MaxMessageSize)
"--- Replicated to B (same names, B's ids)"
$R = Wait-Query "SELECT message_id, length(message_data), topic_id, node_id FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id" $OnB '"4","40"' 60
Expect "every one on B, under logs=300 kitchen=30" $R ('\[\["1","{0}","300","30"\],\["2","{1}","300","30"\],\["3","{2}","300","30"\],\["4","40","300","30"\]\]' -f $Sizes["m100k"], $Sizes["m1m"], $MaxMessageSize)
$R = Query "SELECT count(*) FROM data a WHERE node_id = 30 AND message_id = 3 AND substr(message_data, 1, 31) = '{`"n`":`"mmax`",`"pad`":`"0123456789ab' AND substr(message_data, -2) = '`"}' AND is_json = 1" $OnB
Expect "the biggest one is intact on B" $R '\[\["1"\]\]'
"--- Read back the biggest, from B"
# Pushed after the small one, so it's the latest.
$Id++
Expect "push the biggest again" (Tool "BakaShrotPushMessage.exe" @($Files["mmax"], $OnA)) "message #$Id"
$null = Wait-Query "SELECT max(message_id) FROM data WHERE node_id = 30" $OnB "`"$Id`"" 60
$T = Measure-Command { $O = & (Join-Path $Build "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1 }
$Code = $LASTEXITCODE
$Json = if ($O.Count -ge 2) { [string]$O[1] } else { "" }
Check ("BakaShrotGetLatestMessage of {0:N0} bytes from B ({1:N0} ms)" -f $MaxMessageSize, $T.TotalMilliseconds) ($Code -eq 0 -and $Json.Length -eq $MaxMessageSize -and $Json -eq [IO.File]::ReadAllText($Files["mmax"].Substring(1))) ("[$Code] " + [string]$O[0] + ", " + $Json.Length + " chars")
"--- Many small ones still go in batches"
1..30 | ForEach-Object { $null = Tool "BakaShrotPushMessage.exe" @($Small, $OnA) }
$R = Wait-Query "SELECT count(*) FROM data WHERE node_id = 30" $OnB '"35"' 30
Expect "35 on B" $R '\[\["35"\]\]'
"--- Not JSON: stored as is, flagged"
Expect "1 MB of broken JSON is stored" (Tool "BakaShrotPushMessage.exe" @("@$Broken", $OnA)) "message #36"
Expect "plain text is stored" (Tool "BakaShrotPushMessage.exe" @("@$Text", $OnA)) "message #37"
Expect "flagged is_json = 0 on A, the rest 1" (Query "SELECT message_id, is_json, length(message_data) FROM data WHERE node_id = 2 AND message_id >= 35 ORDER BY message_id" $OnA) '\[\["35","1","40"\],\["36","0","1000000"\],\["37","0","24"\]\]'
$R = Wait-Query "SELECT message_id, is_json, length(message_data) FROM data WHERE node_id = 30 AND message_id >= 35 ORDER BY message_id" $OnB '"37"' 30
Expect "replicated and flagged the same on B" $R '\[\["35","1","40"\],\["36","0","1000000"\],\["37","0","24"\]\]'
$O = & (Join-Path $Build "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1
Check "read back as is from B" ($LASTEXITCODE -eq 0 -and [string]$O[1] -eq "just some text, not JSON") ($O -join " | ")
"--- is_json for the edge cases (SQLite's json_valid(), RFC 8259)"
$Cases = @(
@("42", 1), @('"a string"', 1), @("null", 1), @("[1,2]", 1), @(' {"a":1} ', 1),
@("{a:1}", 0), @('{"a":1} x', 0), @("{'a':1}", 0), @('{"a":1', 0), @("", 0))
$Id = 37
foreach ($C in $Cases) {
$Id++
$F = Join-Path $Dir "case$Id.txt"
[IO.File]::WriteAllText($F, $C[0])
$R = Tool "BakaShrotPushMessage.exe" @("@$F", $OnA)
$Q = Query "SELECT is_json FROM data WHERE node_id = 2 AND message_id = $Id" $OnA
Check ("'{0}' stored, is_json = {1}" -f $C[0], $C[1]) ($R.Out -match "message #$Id" -and $Q.Out -match ('"rows":\[\["{0}"\]\]' -f $C[1])) ($R.Out + " / " + $Q.Out)
}
"--- JSON queries over mixed rows"
Expect "with is_json = 1, ->> works" (Query "SELECT COUNT(*) FROM data WHERE is_json = 1 AND message_data ->> '$.n' = 'small'" $OnA) '\[\["31"\]\]'
Expect "in the select list too" (Query "SELECT COUNT(message_data ->> '$.n') FROM data WHERE is_json = 1" $OnA) '\[\["35"\]\]'
# SQLite fails these with "malformed JSON" on the first non-JSON row.
# PureBasic's NextDatabaseRow() can't tell that from the end of the rows,
# RunReadOnlyQuery() asks SQLite: refused, never a partial or empty answer.
Expect "without it, an aggregate is refused with SQLite's error, not answered with no rows" (Query "SELECT COUNT(*) FROM data WHERE message_data ->> '$.n' = 'small'" $OnA) 'Query failed: malformed JSON \(a row isn''t JSON: add is_json = 1 to the WHERE\)' 1
Expect "rows read as they go are refused too, not cut short at the first non-JSON one" (Query "SELECT message_id, message_data ->> '$.n' FROM data WHERE node_id = 2 ORDER BY message_id" $OnA) 'Query failed: malformed JSON' 1
Expect "non-JSON rows without JSON functions: every row" (Query "SELECT COUNT(*), SUM(is_json = 0) FROM data" $OnA) '\[\["\d+","\d+"\]\]'
Expect "JSON functions guarded by CASE WHEN is_json: every row" (Query "SELECT COUNT(*), COUNT(CASE WHEN is_json THEN message_data ->> '$.n' END) FROM data" $OnA) '\[\["\d+","35"\]\]'
Expect "a query with really no rows: still an empty answer" (Query "SELECT message_id FROM data WHERE message_id < 0" $OnA) '"rows":\[\]'
Expect "and a query error still refused as before" (Query "SELECT nope FROM data" $OnA) 'Query failed: .*nope' 1
} finally {
Stop-Srv $SA; Stop-Srv $SB
}
"--- Logs"
# Up to the last real activity: whichever stops first, the other loses its
# link to it.
# A and B start together: until its first link, the other one may not be
# listening yet. Refused at once on Linux, while Windows retries the connect
# for about a second, by which time it usually is. Those attempts are left out.
function Skip-EarlyLinkFailures([string[]]$Lines) {
$Linked = $false
foreach ($Line in $Lines) {
if ($Line -match "^\[Peer\] Linked to") { $Linked = $true }
if ($Linked -or $Line -notmatch "^\[Peer\] (Failed to link|Retrying)") { $Line }
}
}
function Read-Log($Name) {
$L = @(Get-Content (Join-Path $Dir "$Name.log"))
$End = [array]::IndexOf($L, "Stopping...")
if ($End -lt 0) { $End = $L.Count }
while ($End -gt 0 -and $L[$End - 1] -match "Lost the link|Dropping the link|Retrying|disconnected|aborted|didn't answer") { $End-- }
@(Skip-EarlyLinkFailures $L[0..([math]::Max($End - 1, 0))]) -join "`n"
}
$LogA = Read-Log "a"
$LogB = Read-Log "b"
# The raw frames are cut as an invalid frame, or as too much data when the
# zeros after the header filled the inbox before its size was checked:
# either way right away, which one is down to timing.
# Client ids get reused, so whether each one is authenticated is followed
# line by line, from its "connected".
$Authenticated = @{}; $Cut = 0; $CutAuthenticated = 0
foreach ($Line in ($LogA -split "`n")) {
if ($Line -match "Client (\d+) connected") { $Authenticated[$Matches[1]] = $false }
elseif ($Line -match "Client (\d+) authenticated") { $Authenticated[$Matches[1]] = $true }
elseif ($Line -match "Client (\d+) sent (an invalid frame|too much data)") {
$Cut++
if ($Authenticated[$Matches[1]]) { $CutAuthenticated++ }
}
}
Check "A cut both raw frames (invalid frame or too much data)" ($Cut -ge 2) "$Cut times"
Check "none of them from an authenticated client" ($CutAuthenticated -eq 0) "$CutAuthenticated"
# Without the refusals this test asks for ("Query failed: malformed JSON", ...).
$UnrefusedA = ($LogA -split "`n" | Where-Object { $_ -notmatch "Refused a request" }) -join "`n"
$UnrefusedB = ($LogB -split "`n" | Where-Object { $_ -notmatch "Refused a request" }) -join "`n"
foreach ($P in @("too big", "Lost the link", "Failed")) {
Check "no '$P' in A's or B's log" (-not ($UnrefusedA -match [regex]::Escape($P)) -and -not ($UnrefusedB -match [regex]::Escape($P))) "checked"
}
Check "no 'sent too much data' in B's log" (-not ($LogB -match "sent too much data")) "checked"
""
if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" }
+404
View File
@@ -0,0 +1,404 @@
;{- Code Header
; ==- Basic Info -================================
; Name: CipherTest.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; Tests of Commons/Cryptography/Cipher.pbi, no sockets: round trips in both
; directions, and everything that must be refused (tampering, replay,
; reordering, reflection, wrong key), empty and 16 MB buffers.
; And of Session.pbi: the sealed Hello (only its server opens it, tampering
; refused) and the key exchange (both ends agree, a swapped half or another
; connection's keys don't work, the key pairs are wiped).
; Compile as a console program into Build\ (libsodium.dll is there), run it
; from there. Exits with 0 if every check passed, 1 otherwise.
; ============================================================================
EnableExplicit
XIncludeFile "../Commons/Cryptography/Session.pbi"
Global Fails.i = 0
Procedure Check(What.s, Ok.i, Detail.s = "")
If Ok
PrintN("PASS " + What)
Else
PrintN("FAIL " + What)
Fails + 1
EndIf
If Detail <> ""
PrintN(" -> " + Detail)
EndIf
EndProcedure
; Text as a UTF-8 buffer, its size in *Size\i.
Procedure.i ToUtf8(Text.s, *Size.Integer)
Protected *Buffer
*Size\i = StringByteLength(Text, #PB_UTF8)
*Buffer = AllocateMemory(*Size\i + 1)
PokeS(*Buffer, Text, -1, #PB_UTF8)
ProcedureReturn *Buffer
EndProcedure
; Encrypts Text with *From, decrypts it with *To, returns what came out ("" and
; *Ok\i #False if refused).
Procedure.s RoundTrip(*From.BakaShrot_Cipher, *To.BakaShrot_Cipher, Text.s, *Ok.Integer)
Protected *Plain, PlainSize.Integer, *Sealed, SealedSize.Integer, *Opened, OpenedSize.Integer, Result.s
*Ok\i = #False
*Plain = ToUtf8(Text, @PlainSize)
*Sealed = BakaShrot_Cipher_Encrypt(*From, *Plain, PlainSize\i, @SealedSize)
FreeMemory(*Plain)
If Not *Sealed
ProcedureReturn ""
EndIf
*Opened = BakaShrot_Cipher_Decrypt(*To, *Sealed, SealedSize\i, @OpenedSize)
FreeMemory(*Sealed)
If Not *Opened
ProcedureReturn ""
EndIf
Result = PeekS(*Opened, OpenedSize\i, #PB_UTF8 | #PB_ByteLength)
FreeMemory(*Opened)
*Ok\i = #True
ProcedureReturn Result
EndProcedure
; Whether Text's UTF-8 bytes appear anywhere in *Buffer (Size bytes).
Procedure.i ContainsText(*Buffer, Size.i, Text.s)
Protected *Needle, NeedleSize.Integer, i.i, Found.i
*Needle = ToUtf8(Text, @NeedleSize)
For i = 0 To Size - NeedleSize\i
If CompareMemory(*Buffer + i, *Needle, NeedleSize\i)
Found = #True
Break
EndIf
Next
FreeMemory(*Needle)
ProcedureReturn Found
EndProcedure
; Whether *Sealed (Size bytes) is refused by *To, without changing it.
Procedure.i IsRefused(*To.BakaShrot_Cipher, *Sealed, Size.i)
Protected *Opened, OpenedSize.Integer
*Opened = BakaShrot_Cipher_Decrypt(*To, *Sealed, Size, @OpenedSize)
If *Opened
FreeMemory(*Opened)
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; A copy of Size bytes at *Source.
Procedure.i Copy(*Source, Size.i)
Protected *Copy = AllocateMemory(Size)
CopyMemory(*Source, *Copy, Size)
ProcedureReturn *Copy
EndProcedure
Define *Key, *OtherKey
Define Client.BakaShrot_Cipher, Server.BakaShrot_Cipher, Other.BakaShrot_Cipher, Uninitialized.BakaShrot_Cipher
Define Ok.Integer, Text.s, i.i, Zero.i
Define *Plain, PlainSize.Integer, *Sealed, SealedSize.Integer, *Sealed2, Sealed2Size.Integer, *Opened, OpenedSize.Integer
Define *Tampered, Offset.i, Refused.i, StartTime.q, Elapsed.q
OpenConsole()
If Not InitCryptography()
PrintN("FAIL libsodium couldn't initialize")
End 1
EndIf
*Key = AllocateMemory(#BakaShrot_Cipher_KeySize)
*OtherKey = AllocateMemory(#BakaShrot_Cipher_KeySize)
BakaShrot_Cipher_GenerateKey(*Key)
BakaShrot_Cipher_GenerateKey(*OtherKey)
Check("Two generated keys differ", Bool(Not CompareMemory(*Key, *OtherKey, #BakaShrot_Cipher_KeySize)))
Check("Init as client", BakaShrot_Cipher_Init(@Client, *Key, #BakaShrot_Cipher_Client))
Check("Init as server", BakaShrot_Cipher_Init(@Server, *Key, #BakaShrot_Cipher_Server))
Check("Init with role 0 refused", Bool(Not BakaShrot_Cipher_Init(@Other, *Key, 0)))
; --- Round trips ---------------------------------------------------------------
Text = RoundTrip(@Client, @Server, "hello, server", @Ok)
Check("Client -> server", Bool(Ok\i And Text = "hello, server"), Text)
Text = RoundTrip(@Server, @Client, "hello, client", @Ok)
Check("Server -> client", Bool(Ok\i And Text = "hello, client"), Text)
For i = 1 To 100
Text = RoundTrip(@Client, @Server, "message " + Str(i), @Ok)
If Not Ok\i Or Text <> "message " + Str(i)
Break
EndIf
Next
Check("100 more in order", Bool(i = 101), Str(i - 1) + " went through")
Text = RoundTrip(@Client, @Server, "héllo wörld, 🌍", @Ok)
Check("Non-ASCII data", Bool(Ok\i And Text = "héllo wörld, 🌍"), Text)
; --- What a sealed buffer looks like ------------------------------------------
*Plain = ToUtf8("same text", @PlainSize)
*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize)
*Sealed2 = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @Sealed2Size)
Check("Sealed size is the data + " + Str(#BakaShrot_Cipher_Overhead), Bool(SealedSize\i = PlainSize\i + #BakaShrot_Cipher_Overhead), Str(SealedSize\i) + " bytes for " + Str(PlainSize\i))
Check("The data doesn't appear in it", Bool(Not CompareMemory(*Sealed + #BakaShrot_Cipher_SequenceSize, *Plain, PlainSize\i)))
Check("The same data twice seals differently", Bool(Not CompareMemory(*Sealed + #BakaShrot_Cipher_SequenceSize, *Sealed2 + #BakaShrot_Cipher_SequenceSize, PlainSize\i)))
Check("Each carries its sequence number", Bool(PeekQ(*Sealed2) = PeekQ(*Sealed) + 1), Str(PeekQ(*Sealed)) + ", " + Str(PeekQ(*Sealed2)))
; --- Refused ---------------------------------------------------------------------
; Reordered: the second one first.
Check("The next-but-one first: refused (reordered)", IsRefused(@Server, *Sealed2, Sealed2Size\i))
; Tampered anywhere: the sequence number, the data, the tag.
Refused = 0
For Offset = 0 To SealedSize\i - 1
*Tampered = Copy(*Sealed, SealedSize\i)
PokeA(*Tampered + Offset, PeekA(*Tampered + Offset) ! $01)
If IsRefused(@Server, *Tampered, SealedSize\i)
Refused + 1
EndIf
FreeMemory(*Tampered)
Next
Check("One bit flipped anywhere: refused, at every one of its " + Str(SealedSize\i) + " bytes", Bool(Refused = SealedSize\i), Str(Refused) + " refused")
Check("Cut short by one byte: refused", IsRefused(@Server, *Sealed, SealedSize\i - 1))
Check("Shorter than the overhead: refused", IsRefused(@Server, *Sealed, #BakaShrot_Cipher_Overhead - 1))
; None of that moved the receiver on: the genuine ones still go through, in order.
*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, SealedSize\i, @OpenedSize)
Check("After all that, the genuine one still decrypts", Bool(*Opened And OpenedSize\i = PlainSize\i And CompareMemory(*Opened, *Plain, PlainSize\i)))
If *Opened : FreeMemory(*Opened) : EndIf
Check("Replayed: refused", IsRefused(@Server, *Sealed, SealedSize\i))
*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed2, Sealed2Size\i, @OpenedSize)
Check("Then the next one", Bool(*Opened <> 0))
If *Opened : FreeMemory(*Opened) : EndIf
; Reflected: sent back to its sender, or to another client with the same key.
*Sealed2 = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @Sealed2Size)
BakaShrot_Cipher_Init(@Other, *Key, #BakaShrot_Cipher_Client)
; Same sequence number, so only the direction differs.
Other\ReceiveSequence = PeekQ(*Sealed2)
Check("Reflected to a client with the same key, same sequence number: refused", IsRefused(@Other, *Sealed2, Sealed2Size\i))
; Another key.
BakaShrot_Cipher_Init(@Other, *OtherKey, #BakaShrot_Cipher_Server)
Other\ReceiveSequence = PeekQ(*Sealed2)
Check("Another key: refused", IsRefused(@Other, *Sealed2, Sealed2Size\i))
FreeMemory(*Sealed)
FreeMemory(*Sealed2)
FreeMemory(*Plain)
Check("Not set up: refuses to encrypt", Bool(BakaShrot_Cipher_Encrypt(@Uninitialized, @Zero, 4, @SealedSize) = 0))
; --- Sizes ---------------------------------------------------------------------
BakaShrot_Cipher_Init(@Client, *Key, #BakaShrot_Cipher_Client)
BakaShrot_Cipher_Init(@Server, *Key, #BakaShrot_Cipher_Server)
*Sealed = BakaShrot_Cipher_Encrypt(@Client, 0, 0, @SealedSize)
*Opened = 0
If *Sealed
*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, SealedSize\i, @OpenedSize)
EndIf
Check("Empty data: sealed in " + Str(#BakaShrot_Cipher_Overhead) + " bytes, opens to 0 bytes", Bool(*Sealed And SealedSize\i = #BakaShrot_Cipher_Overhead And *Opened And OpenedSize\i = 0))
If *Sealed : FreeMemory(*Sealed) : EndIf
If *Opened : FreeMemory(*Opened) : EndIf
PlainSize\i = 16 * 1024 * 1024
*Plain = AllocateMemory(PlainSize\i)
RandomData(*Plain, PlainSize\i)
StartTime = ElapsedMilliseconds()
*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize)
*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, SealedSize\i, @OpenedSize)
Elapsed = ElapsedMilliseconds() - StartTime
Check("16 MB both ways, intact", Bool(*Opened And OpenedSize\i = PlainSize\i And CompareMemory(*Opened, *Plain, PlainSize\i)), Str(Elapsed) + " ms to encrypt and decrypt")
FreeMemory(*Plain)
If *Sealed : FreeMemory(*Sealed) : EndIf
If *Opened : FreeMemory(*Opened) : EndIf
; --- A key per direction -----------------------------------------------------
Check("Two keys: the same one twice refused", Bool(Not BakaShrot_Cipher_InitWithKeys(@Client, *Key, *Key)))
Check("Two keys: client sends with A, receives with B", BakaShrot_Cipher_InitWithKeys(@Client, *Key, *OtherKey))
Check("Two keys: server the other way around", BakaShrot_Cipher_InitWithKeys(@Server, *OtherKey, *Key))
Text = RoundTrip(@Client, @Server, "with two keys", @Ok)
Check("Two keys: client -> server", Bool(Ok\i And Text = "with two keys"), Text)
Text = RoundTrip(@Server, @Client, "and back", @Ok)
Check("Two keys: server -> client", Bool(Ok\i And Text = "and back"), Text)
BakaShrot_Cipher_InitWithKeys(@Other, *Key, *OtherKey)
*Plain = ToUtf8("to myself", @PlainSize)
*Sealed = BakaShrot_Cipher_Encrypt(@Other, *Plain, PlainSize\i, @SealedSize)
Check("Two keys: reflected to its sender, refused", IsRefused(@Other, *Sealed, SealedSize\i))
FreeMemory(*Sealed)
FreeMemory(*Plain)
; --- Clear -------------------------------------------------------------------------
BakaShrot_Cipher_Clear(@Client)
Zero = #True
For i = 0 To #BakaShrot_Cipher_KeySize - 1
If Client\SendKey[i] Or Client\ReceiveKey[i]
Zero = #False
EndIf
Next
Check("Clear wipes both keys", Zero)
Check("Cleared: refuses to encrypt", Bool(BakaShrot_Cipher_Encrypt(@Client, @Zero, 4, @SealedSize) = 0))
sodium_memzero(*Key, #BakaShrot_Cipher_KeySize)
sodium_memzero(*OtherKey, #BakaShrot_Cipher_KeySize)
; --- Into a given buffer ---------------------------------------------------------
BakaShrot_Cipher_Init(@Client, *Key, #BakaShrot_Cipher_Client)
BakaShrot_Cipher_Init(@Server, *Key, #BakaShrot_Cipher_Server)
*Plain = ToUtf8("in place", @PlainSize)
*Sealed = AllocateMemory(PlainSize\i + #BakaShrot_Cipher_Overhead)
Check("EncryptTo writes a sealed buffer", BakaShrot_Cipher_EncryptTo(@Client, *Plain, PlainSize\i, *Sealed))
*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, PlainSize\i + #BakaShrot_Cipher_Overhead, @OpenedSize)
Check("EncryptTo's buffer decrypts", Bool(*Opened And PeekS(*Opened, OpenedSize\i, #PB_UTF8 | #PB_ByteLength) = "in place"))
If *Opened : FreeMemory(*Opened) : EndIf
Check("EncryptTo refuses without a cipher", Bool(Not BakaShrot_Cipher_EncryptTo(@Uninitialized, *Plain, PlainSize\i, *Sealed)))
FreeMemory(*Sealed)
FreeMemory(*Plain)
BakaShrot_Cipher_Clear(@Client)
BakaShrot_Cipher_Clear(@Server)
; --- Session: the sealed Hello ---------------------------------------------------
Define *ServerPublic = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize)
Define *ServerPrivate = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize)
Define *OtherPublic = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize)
Define *OtherPrivate = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize)
Define *ZeroKey = AllocateMemory(32)
Define HelloKeys.BakaShrot_HelloKeys, OtherHelloKeys.BakaShrot_HelloKeys
Define ClientPair.BakaShrot_SessionKeyPair, ServerPair.BakaShrot_SessionKeyPair, MiddlePair.BakaShrot_SessionKeyPair
Define ClientHalf.BakaShrot_SessionKey, ServerHalf.BakaShrot_SessionKey, MiddleHalf.BakaShrot_SessionKey
GenerateKeyPair(*ServerPublic, *ServerPrivate)
GenerateKeyPair(*OtherPublic, *OtherPrivate)
Check("Hello keys from a server's private key", BakaShrot_Session_LoadHelloKeys(@HelloKeys, *ServerPrivate))
BakaShrot_Session_LoadHelloKeys(@OtherHelloKeys, *OtherPrivate)
*Plain = ToUtf8("hello, I'm logs:kitchen", @PlainSize)
*Sealed = BakaShrot_Session_SealHello(*ServerPublic, *Plain, PlainSize\i, @SealedSize)
Check("Hello sealed, 48 bytes more", Bool(*Sealed And SealedSize\i = PlainSize\i + #BakaShrot_SealedBoxOverhead))
Check("The sealed hello doesn't show the identity", Bool(*Sealed And Not ContainsText(*Sealed, SealedSize\i, "kitchen")))
*Opened = BakaShrot_Session_OpenHello(@HelloKeys, *Sealed, SealedSize\i, @OpenedSize)
Check("The server opens it", Bool(*Opened And PeekS(*Opened, OpenedSize\i, #PB_UTF8 | #PB_ByteLength) = "hello, I'm logs:kitchen"))
If *Opened : FreeMemory(*Opened) : EndIf
*Opened = BakaShrot_Session_OpenHello(@OtherHelloKeys, *Sealed, SealedSize\i, @OpenedSize)
Check("Another server can't open it", Bool(Not *Opened))
If *Opened : FreeMemory(*Opened) : EndIf
Refused = #True
For Offset = 0 To SealedSize\i - 1 Step 7
*Tampered = Copy(*Sealed, SealedSize\i)
PokeA(*Tampered + Offset, PeekA(*Tampered + Offset) ! $01)
*Opened = BakaShrot_Session_OpenHello(@HelloKeys, *Tampered, SealedSize\i, @OpenedSize)
If *Opened
Refused = #False
FreeMemory(*Opened)
EndIf
FreeMemory(*Tampered)
Next
Check("A tampered hello isn't opened", Refused)
*Opened = BakaShrot_Session_OpenHello(@HelloKeys, *Sealed, #BakaShrot_SealedBoxOverhead, @OpenedSize)
Check("A hello cut short isn't opened", Bool(Not *Opened))
FreeMemory(*Sealed)
*Sealed = BakaShrot_Session_SealHello(*ZeroKey, *Plain, PlainSize\i, @SealedSize)
Check("Sealing for an invalid server key refused", Bool(Not *Sealed))
If *Sealed : FreeMemory(*Sealed) : EndIf
FreeMemory(*Plain)
; --- Session: the key exchange ---------------------------------------------------
BakaShrot_Session_NewKeyPair(@ClientPair)
BakaShrot_Session_NewKeyPair(@ServerPair)
CopyMemory(@ClientPair\PublicKey[0], @ClientHalf, 32)
CopyMemory(@ServerPair\PublicKey[0], @ServerHalf, 32)
Check("Server starts from the client's half", BakaShrot_Session_StartServer(@Server, @ServerPair, @ClientHalf))
Check("Client starts from the server's half", BakaShrot_Session_StartClient(@Client, @ClientPair, @ServerHalf))
Zero = #True
For i = 0 To #BakaShrot_X25519_SecretKeySize - 1
If ClientPair\SecretKey[i] Or ServerPair\SecretKey[i]
Zero = #False
EndIf
Next
Check("Both key pairs wiped once started", Zero)
Text = RoundTrip(@Client, @Server, "push over a session", @Ok)
Check("Session: client -> server", Bool(Ok\i And Text = "push over a session"), Text)
Text = RoundTrip(@Server, @Client, "answer over a session", @Ok)
Check("Session: server -> client", Bool(Ok\i And Text = "answer over a session"), Text)
Check("Session: a key per direction", Bool(Not CompareMemory(@Client\SendKey[0], @Client\ReceiveKey[0], #BakaShrot_Cipher_KeySize)))
Check("Session: the client's send key is the server's receive key", CompareMemory(@Client\SendKey[0], @Server\ReceiveKey[0], #BakaShrot_Cipher_KeySize))
*Plain = ToUtf8("back to me", @PlainSize)
*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize)
Check("Session: reflected to the client, refused", IsRefused(@Client, *Sealed, SealedSize\i))
FreeMemory(*Sealed)
; Someone in the middle swapping the server's half for theirs: the client
; ends up with keys the real server doesn't have. (The server's signature
; of the halves catches it first, in the handshake.)
BakaShrot_Session_NewKeyPair(@ClientPair)
BakaShrot_Session_NewKeyPair(@ServerPair)
BakaShrot_Session_NewKeyPair(@MiddlePair)
CopyMemory(@ClientPair\PublicKey[0], @ClientHalf, 32)
CopyMemory(@MiddlePair\PublicKey[0], @MiddleHalf, 32)
BakaShrot_Session_StartServer(@Server, @ServerPair, @ClientHalf)
BakaShrot_Session_StartClient(@Client, @ClientPair, @MiddleHalf)
*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize)
Check("Session: halves swapped, the server can't decrypt", IsRefused(@Server, *Sealed, SealedSize\i))
FreeMemory(*Sealed)
; Another connection of the same client gets other keys.
Define Server2.BakaShrot_Cipher
CopyMemory(@Server, @Other, SizeOf(BakaShrot_Cipher))
BakaShrot_Session_NewKeyPair(@ClientPair)
BakaShrot_Session_NewKeyPair(@ServerPair)
CopyMemory(@ClientPair\PublicKey[0], @ClientHalf, 32)
CopyMemory(@ServerPair\PublicKey[0], @ServerHalf, 32)
BakaShrot_Session_StartServer(@Server2, @ServerPair, @ClientHalf)
BakaShrot_Session_StartClient(@Client, @ClientPair, @ServerHalf)
Check("Session: another connection, other keys", Bool(Not CompareMemory(@Server2\ReceiveKey[0], @Other\ReceiveKey[0], #BakaShrot_Cipher_KeySize)))
*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize)
Check("Session: replayed into another connection, refused", IsRefused(@Other, *Sealed, SealedSize\i))
FreeMemory(*Sealed)
FreeMemory(*Plain)
BakaShrot_Session_NewKeyPair(@ServerPair)
Check("Session: an all-zero half refused", Bool(Not BakaShrot_Session_StartServer(@Server, @ServerPair, *ZeroKey)))
Check("Session: refused, the cipher isn't usable", Bool(Not Server\IsReady))
BakaShrot_Session_ClearHelloKeys(@HelloKeys)
BakaShrot_Session_ClearHelloKeys(@OtherHelloKeys)
sodium_memzero(*ServerPrivate, #BakaShrot_Ed25519_PrivateKeySize)
sodium_memzero(*OtherPrivate, #BakaShrot_Ed25519_PrivateKeySize)
BakaShrot_Cipher_Clear(@Client)
BakaShrot_Cipher_Clear(@Server)
BakaShrot_Cipher_Clear(@Server2)
BakaShrot_Cipher_Clear(@Other)
PrintN("")
If Fails
PrintN(Str(Fails) + " check(s) failed")
End 1
EndIf
PrintN("All checks passed")
End 0
+251
View File
@@ -0,0 +1,251 @@
# End-to-end test of reading runs of messages: the GetMessages request
# (Commons/Networking/Packets/GetMessagesPacket.pbi), through the client DLL
# and Tools\BakaShrotGetMessages: from the start, after an id, after the latest one,
# with a limit, answers split at ~1 MB, data that isn't JSON or spans lines,
# refusals, and --follow picking up new pushes.
# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe (Bench-Replication.ps1,
# or compile Tests\Bench\BenchServer.pb into it). Uses port 12405.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\GetMessages-Test.ps1
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"))
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_getmessagestest"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Port = 12405
$Fails = 0
function New-KeyPair {
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
$C = New-Object System.Net.Sockets.TcpClient
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
}
# Runs a tool, its output as lines (Lines) and joined (Out).
function Tool([string]$Name, [string[]]$A) {
$O = @(& (Join-Path $Build $Name) @A 2>&1 | ForEach-Object { "$_" })
@{ Code = $LASTEXITCODE; Lines = $O; Out = ($O -join " | ") }
}
function Check([string]$What, [bool]$Ok, [string]$Detail) {
if (-not $Ok) { $script:Fails++ }
if ($Detail.Length -gt 300) { $Detail = $Detail.Substring(0, 300) + "... (" + $Detail.Length + " chars)" }
"{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail
}
function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) {
Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out)
}
# The ids BakaShrotGetMessages printed, in order.
function Ids($Result) {
@($Result.Lines | Where-Object { $_ -match "^\d+`t" } | ForEach-Object { [long]($_ -split "`t", 2)[0] })
}
# Whether Ids are exactly From..To.
function Is-Run($Ids, [long]$From, [long]$To) {
$Want = if ($To -ge $From) { @($From..$To) } else { @() }
($Ids -join ",") -eq ($Want -join ",")
}
function Push($Data, $Ini, [string]$Topic = "") {
$F = Join-Path $Dir "push.txt"
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
$A = @()
if ($Topic) { $A += @("-t", $Topic) }
Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini))
}
$S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair
Set-Content (Join-Path $Dir "server.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($S.Priv)
Node = server
[BakaShrot.Topics]
logs = 1
secret = 2
[BakaShrot.Nodes]
server = 1
kitchen = 5
lounge = 6
empty = 7
[BakaShrot.Server]
Host = 127.0.0.1
Port = $Port
DatabasePath = $(Join-Path $Dir "server.sqlite")
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Node = kitchen
DefaultTopic = logs
PushTopics = logs;secret
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.lounge]
PublicKeys = $($L.Pub)
Node = lounge
DefaultTopic = logs
ReadTopics = logs
"@
function Client-Ini($Name, $Keys) {
$P = Join-Path $Dir "$Name.ini"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)"
$P
}
$Kitchen = Client-Ini "kitchen" $K
$Lounge = Client-Ini "lounge" $L
if (Test-Port $Port) { throw "Port $Port is already in use" }
$Stop = Join-Path $Dir "server.stop"
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "server.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput (Join-Path $Dir "server.log") -WindowStyle Hidden -PassThru
$null = $P.Handle
$Follower = $null
try {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($P.HasExited) { throw "The server exited: $(Get-Content (Join-Path $Dir "server.log") -Raw)" }
if ((Get-Date) -gt $D) { throw "The server isn't listening" }
Start-Sleep -Milliseconds 100
}
# --- Nothing yet ----------------------------------------------------------
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", $Kitchen)
Check "No messages yet: nothing printed, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen)
Check "--after latest with no messages yet: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
# --- 120 small ones -------------------------------------------------------
$Started = Get-Date
$Pushed = 0
for ($i = 1; $i -le 120; $i++) {
$R = Push ('{"i":' + $i + '}') $Kitchen
if ($R.Code -eq 0) { $Pushed++ }
}
Check "120 pushes" ($Pushed -eq 120) ("{0} pushed in {1:N1} s" -f $Pushed, ((Get-Date) - $Started).TotalSeconds)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", $Kitchen)
$Ids = Ids $R
Check "Default: the first 100, in order" ($R.Code -eq 0 -and (Is-Run $Ids 1 100)) ("[{0}] {1} ids, {2}..{3}" -f $R.Code, $Ids.Count, $Ids[0], $Ids[-1])
Check "Each line is the id, a tab and the data as stored" ($R.Lines[0] -eq "1`t{`"i`":1}" -and $R.Lines[99] -eq "100`t{`"i`":100}") ("'{0}' / '{1}'" -f $R.Lines[0], $R.Lines[99])
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--limit", "0", $Kitchen)
Check "--limit 0: all 120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 1 120)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "115", $Kitchen)
Check "--after 115: 116-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 116 120)) ("[{0}] {1}" -f $R.Code, $R.Out)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "10", "--limit", "7", $Kitchen)
Check "--after 10 --limit 7: 11-17" ($R.Code -eq 0 -and (Is-Run (Ids $R) 11 17)) ("[{0}] {1}" -f $R.Code, $R.Out)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen)
Check "--after the last one: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen)
Check "--after latest: nothing" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
$R = Tool "BakaShrotGetMessages.exe" @("1", "5", "--after", "118", $Kitchen)
Check "By ids (1, 5): 119-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 119 120)) ("[{0}] {1}" -f $R.Code, $R.Out)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "100", $Lounge)
Check "Another client allowed to read logs: 101-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 101 120)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count)
# --- Refusals -------------------------------------------------------------
$null = Push '{"s":1}' $Kitchen "secret"
$R = Tool "BakaShrotGetMessages.exe" @("secret", "kitchen", $Kitchen)
Check "A topic in ReadTopics (*): read" ($R.Code -eq 0 -and (Is-Run (Ids $R) 1 1)) ("[{0}] {1}" -f $R.Code, $R.Out)
Expect "A topic not in ReadTopics: refused" (Tool "BakaShrotGetMessages.exe" @("secret", "kitchen", $Lounge)) "Not allowed to read topic 'secret'" 1
Expect "Unknown node: refused" (Tool "BakaShrotGetMessages.exe" @("logs", "nobody", $Kitchen)) "Unknown node 'nobody'" 1
Expect "Unknown topic: refused" (Tool "BakaShrotGetMessages.exe" @("nothing", "kitchen", $Kitchen)) "Unknown topic 'nothing'" 1
$R = Tool "BakaShrotGetMessages.exe" @("logs", "empty", $Kitchen)
Check "A known node with no messages: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
Expect "Bad --after: refused by the tool" (Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "-3", $Kitchen)) "Invalid --after" 1
Expect "Unknown option: refused by the tool" (Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--nope", $Kitchen)) "Unknown option" 1
# --- Data that isn't one line of JSON -------------------------------------
$null = Push "plain text, not JSON" $Kitchen
$null = Push "two`nlines" $Kitchen
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen)
Check "Non-JSON data printed as stored, a line break spans lines" (
$R.Code -eq 0 -and $R.Lines.Count -eq 3 -and $R.Lines[0] -eq "121`tplain text, not JSON" -and $R.Lines[1] -eq "122`ttwo" -and $R.Lines[2] -eq "lines"
) ($R.Lines -join " / ")
# --- Answers split at ~1 MB -----------------------------------------------
# 5 of 600 KB and one of 3 MB: one per answer, the big one alone.
$Sizes = @(600KB, 600KB, 600KB, 3MB, 600KB, 600KB)
$BigOk = 0
foreach ($Size in $Sizes) {
$Data = '{"pad":"' + ("x" * ($Size - 10)) + '"}'
if ((Push $Data $Kitchen).Code -eq 0) { $BigOk++ }
}
Check "6 big pushes (5 x 600 KB, 3 MB)" ($BigOk -eq 6) "$BigOk pushed"
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "122", $Kitchen)
$Ids = Ids $R
$Lengths = @($R.Lines | ForEach-Object { (($_ -split "`t", 2)[1]).Length })
$WantLengths = @($Sizes | ForEach-Object { $_ })
Check "All 6 read back whole, over several answers" (
$R.Code -eq 0 -and (Is-Run $Ids 123 128) -and (($Lengths -join ",") -eq ($WantLengths -join ","))
) ("[{0}] ids {1}, lengths {2}" -f $R.Code, ($Ids -join ","), ($Lengths -join ","))
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "122", "--limit", "2", $Kitchen)
Check "--limit 2 over big ones: 123-124" ($R.Code -eq 0 -and (Is-Run (Ids $R) 123 124)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count)
# --- --follow ---------------------------------------------------------------
$FollowOut = Join-Path $Dir "follow.out"
$Follower = Start-Process -FilePath (Join-Path $Build "BakaShrotGetMessages.exe") `
-ArgumentList "logs", "kitchen", "--after", "latest", "--follow", "--interval", "100", "`"$Kitchen`"" `
-WorkingDirectory $Build -RedirectStandardOutput $FollowOut -WindowStyle Hidden -PassThru
$null = $Follower.Handle
Start-Sleep -Milliseconds 1500
Check "--follow keeps running once caught up" (-not $Follower.HasExited) $(if ($Follower.HasExited) { "exited with $($Follower.ExitCode)" } else { "running" })
$null = Push '{"f":1}' $Kitchen
$null = Push '{"f":2}' $Kitchen
$null = Push '{"f":3}' $Kitchen
$D = (Get-Date).AddSeconds(10)
do {
Start-Sleep -Milliseconds 200
$Lines = @()
try {
$Fs = [IO.File]::Open($FollowOut, "Open", "Read", "ReadWrite")
$Text = (New-Object IO.StreamReader($Fs)).ReadToEnd(); $Fs.Close()
$Lines = @($Text -split "`r?`n" | Where-Object { $_ -ne "" })
} catch { }
} while ($Lines.Count -lt 3 -and (Get-Date) -lt $D)
Check "--follow --after latest: only the 3 new ones" (
$Lines.Count -eq 3 -and $Lines[0] -eq "129`t{`"f`":1}" -and $Lines[2] -eq "131`t{`"f`":3}"
) ($Lines -join " / ")
# The server going away ends it with a failure.
Set-Content $Stop "x"
if (-not $P.WaitForExit(15000)) { Stop-Process -Id $P.Id -Force }
$Ended = $Follower.WaitForExit(15000)
Check "--follow fails once the server is gone" ($Ended -and $Follower.ExitCode -eq 1) $(if ($Ended) { "exit code $($Follower.ExitCode)" } else { "still running" })
$Log = Get-Content (Join-Path $Dir "server.log") -Raw
$Bad = @($Log -split "`r?`n" | Where-Object { $_ -match "invalid|unexpected|Failed" })
Check "Server log: no invalid or unexpected packets" ($Bad.Count -eq 0) $(if ($Bad.Count) { $Bad -join " / " } else { "clean" })
}
finally {
if ($Follower -and -not $Follower.HasExited) { Stop-Process -Id $Follower.Id -Force }
if (-not $P.HasExited) {
Set-Content $Stop "x"
if (-not $P.WaitForExit(15000)) { Stop-Process -Id $P.Id -Force }
}
}
""
if ($Fails -eq 0) { "All checks passed" } else { "$Fails check(s) failed" }
exit $(if ($Fails -eq 0) { 0 } else { 1 })
+177
View File
@@ -0,0 +1,177 @@
;{- Code Header
; ==- Basic Info -================================
; Name: HandshakeTest.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; Simulates the Hello -> ChallengeRequest -> ChallengeResponse handshake
; between a client and a server, without sockets.
; Each "send" is an encoded buffer, each "receive" decodes that same buffer.
;
; Compile as a console program, exits with 0 if everything passed, 1 otherwise.
; The keys and signatures are placeholders, only the packets and the nonce
; check are tested: the cryptography is Tests/CipherTest.pb's.
; ============================================================================
EnableExplicit
XIncludeFile "../Commons/Networking/Packets/HelloPacket.pbi"
XIncludeFile "../Commons/Networking/Packets/ChallengeRequestPacket.pbi"
XIncludeFile "../Commons/Networking/Packets/ChallengeResponsePacket.pbi"
; Prints the result of a check, and stops the test on the first failure.
Procedure Check(Condition.b, Message.s)
If Condition
PrintN("[OK] " + Message)
ProcedureReturn
EndIf
PrintN("[FAIL] " + Message)
End 1
EndProcedure
Define *Wire, WireSize.Integer, *View.MsgPackData
; Client side
Define ClientHello.BakaShrot_AuthHello
Define *ClientChallenge.BakaShrot_ChallengeRequest
Define ClientResponse.BakaShrot_ChallengeResponse
; Server side
Define *ServerHello.BakaShrot_AuthHello
Define ServerChallenge.BakaShrot_ChallengeRequest
Define *ServerResponse.BakaShrot_ChallengeResponse
Define *ServerReplayed.BakaShrot_ChallengeResponse
Define *ServerWrongType.BakaShrot_ChallengeResponse
; Nonce the server keeps for this connection, until the response arrives.
Define *ServerConnectionNonce = AllocateMemory(#BakaShrot_NonceSize)
; Nonce a second connection got, to test a replayed response.
Define *OtherConnectionNonce = AllocateMemory(#BakaShrot_NonceSize)
OpenConsole()
Check(Bool(*ServerConnectionNonce And *OtherConnectionNonce), "Allocated the server's nonce buffers")
Check(Bool(OpenCryptRandom()), "Opened the secure random generator")
; --- 1. Client -> Server: Hello ---------------------------------------------
ClientHello\ClientNode = "34"
ClientHello\ClientPubKeyB64 = "Q2xpZW50UHViS2V5"
Check(Bool(CryptRandomData(@ClientHello\ClientSessionKey[0], #BakaShrot_SessionKeySize)), "Client made a session key")
*Wire = BakaShrot_HelloPacket_Encode(@ClientHello, @WireSize)
Check(Bool(*Wire), "Client encoded its hello")
*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i)
Check(Bool(*View), "Server wrapped the hello")
*ServerHello = BakaShrot_HelloPacket_Decode(*View)
MsgPackFree(*View, #False)
FreeMemory(*Wire)
Check(Bool(*ServerHello), "Server decoded the hello")
Check(Bool(*ServerHello\ClientNode = "34"), "Hello's ClientNode survived")
Check(Bool(*ServerHello\ClientPubKeyB64 = "Q2xpZW50UHViS2V5"), "Hello's ClientPubKeyB64 survived")
Check(CompareMemory(@*ServerHello\ClientSessionKey[0], @ClientHello\ClientSessionKey[0], #BakaShrot_SessionKeySize), "Hello's ClientSessionKey survived")
; --- 2. Server -> Client: ChallengeRequest ----------------------------------
Check(Bool(CryptRandomData(@ServerChallenge\Nonce[0], #BakaShrot_NonceSize)), "Server generated a nonce")
CopyMemory(@ServerChallenge\Nonce[0], *ServerConnectionNonce, #BakaShrot_NonceSize)
ServerChallenge\ChallengeB64 = "U2VydmVyQ2hhbGxlbmdl"
Check(Bool(CryptRandomData(@ServerChallenge\ServerSessionKey[0], #BakaShrot_SessionKeySize)), "Server made a session key")
Check(Bool(CryptRandomData(@ServerChallenge\ServerSignature[0], #BakaShrot_HandshakeSignatureSize)), "Server made a placeholder signature")
*Wire = BakaShrot_ChallengeRequestPacket_Encode(@ServerChallenge, @WireSize)
Check(Bool(*Wire), "Server encoded the challenge request")
*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i)
Check(Bool(*View), "Client wrapped the challenge request")
*ClientChallenge = BakaShrot_ChallengeRequestPacket_Decode(*View)
MsgPackFree(*View, #False)
FreeMemory(*Wire)
Check(Bool(*ClientChallenge), "Client decoded the challenge request")
Check(Bool(*ClientChallenge\ChallengeB64 = "U2VydmVyQ2hhbGxlbmdl"), "Challenge's ChallengeB64 survived")
Check(CompareMemory(@*ClientChallenge\Nonce[0], *ServerConnectionNonce, #BakaShrot_NonceSize), "Challenge's nonce survived")
Check(CompareMemory(@*ClientChallenge\ServerSessionKey[0], @ServerChallenge\ServerSessionKey[0], #BakaShrot_SessionKeySize), "Challenge's ServerSessionKey survived")
Check(CompareMemory(@*ClientChallenge\ServerSignature[0], @ServerChallenge\ServerSignature[0], #BakaShrot_HandshakeSignatureSize), "Challenge's ServerSignature survived")
; --- 3. Client -> Server: ChallengeResponse ---------------------------------
; Placeholder for the real signature of ChallengeB64 + Nonce.
ClientResponse\ChallengeResponseB64 = "U2lnbmVkOiAiU2VydmVyQ2hhbGxlbmdlIg=="
CopyMemory(@*ClientChallenge\Nonce[0], @ClientResponse\Nonce[0], #BakaShrot_NonceSize)
*Wire = BakaShrot_ChallengeResponsePacket_Encode(@ClientResponse, @WireSize)
Check(Bool(*Wire), "Client encoded the challenge response")
*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i)
Check(Bool(*View), "Server wrapped the challenge response")
*ServerResponse = BakaShrot_ChallengeResponsePacket_Decode(*View)
MsgPackFree(*View, #False)
Check(Bool(*ServerResponse), "Server decoded the challenge response")
Check(Bool(*ServerResponse\ChallengeResponseB64 = "U2lnbmVkOiAiU2VydmVyQ2hhbGxlbmdlIg=="), "Response's ChallengeResponseB64 survived")
Check(CompareMemory(@*ServerResponse\Nonce[0], *ServerConnectionNonce, #BakaShrot_NonceSize), "Server accepted the nonce it issued")
; --- 4. Replay: the same response sent on another connection ----------------
; *Wire still holds the response captured in step 3.
Check(Bool(CryptRandomData(*OtherConnectionNonce, #BakaShrot_NonceSize)), "Server generated a nonce for another connection")
*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i)
Check(Bool(*View), "Server wrapped the replayed response")
*ServerReplayed = BakaShrot_ChallengeResponsePacket_Decode(*View)
MsgPackFree(*View, #False)
FreeMemory(*Wire)
Check(Bool(*ServerReplayed), "Replayed response is still a well-formed packet")
Check(Bool(Not CompareMemory(@*ServerReplayed\Nonce[0], *OtherConnectionNonce, #BakaShrot_NonceSize)), "Server rejected the replayed response's nonce")
; --- 5. A hello sent where a challenge response is expected ------------------
*Wire = BakaShrot_HelloPacket_Encode(@ClientHello, @WireSize)
Check(Bool(*Wire), "Client encoded a second hello")
*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i)
Check(Bool(*View), "Server wrapped the misplaced hello")
*ServerWrongType = BakaShrot_ChallengeResponsePacket_Decode(*View)
MsgPackFree(*View, #False)
FreeMemory(*Wire)
Check(Bool(Not *ServerWrongType), "Challenge response decoder rejected a hello")
; --- Cleanup -----------------------------------------------------------------
FreeStructure(*ServerHello)
FreeStructure(*ClientChallenge)
FreeStructure(*ServerResponse)
FreeStructure(*ServerReplayed)
FreeMemory(*ServerConnectionNonce)
FreeMemory(*OtherConnectionNonce)
CloseCryptRandom()
PrintN("")
PrintN("Handshake simulation passed.")
End 0
+478
View File
@@ -0,0 +1,478 @@
# End-to-end test of topic/node names, filters and replication by name:
# two servers with different ids for the same names, strict "named on both
# sides" replication, wildcards (taking undeclared names, filtering),
# old and new config keys, the list tool.
# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe (Bench-Replication.ps1,
# or compile Tests\Bench\BenchServer.pb into it). Uses ports 12401-12402.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\Names-Test.ps1
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"))
$ErrorActionPreference = "Stop"
$Dir = Join-Path $Build "_namestest"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Fails = 0
function New-KeyPair {
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
$C = New-Object System.Net.Sockets.TcpClient
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
}
function Tool([string]$Name, [string[]]$A) {
$O = & (Join-Path $Build $Name) @A 2>&1
@{ Code = $LASTEXITCODE; Out = ($O -join " | ") }
}
function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) {
$Ok = ($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)
if (-not $Ok) { $script:Fails++ }
"{0} {1}`n -> [{2}] {3}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Result.Code, $Result.Out
}
function Start-Srv($Name) {
$Stop = Join-Path $Dir "$Name.stop"
Remove-Item $Stop -ErrorAction SilentlyContinue
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput (Join-Path $Dir "$Name.log") -WindowStyle Hidden -PassThru
$null = $P.Handle
@{ P = $P; Stop = $Stop; Name = $Name }
}
function Stop-Srv($S) {
Set-Content $S.Stop "x"
if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force }
}
function Wait-Port($Port, $S) {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content (Join-Path $Dir "$($S.Name).log") -Raw)" }
if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" }
Start-Sleep -Milliseconds 100
}
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
}
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair; $BC = New-KeyPair; $K2 = New-KeyPair; $R = New-KeyPair
# --- Server A: new keys, logs = 1, sensors = 2 -----------------------------
Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($A.Priv)
Node = serverA
[BakaShrot.Topics]
logs = 1
sensors = 2
secret = 3
sensors.temp = 4
[BakaShrot.Nodes]
serverA = 10
serverB = 11
kitchen = 2
garage = 5
kitchen-2 = 6
blocal = 20
bsecret = 21
reader = 30
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12401
ReplicatingTopics = logs;sensors*
DatabasePath = $(Join-Path $Dir "a.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
[BakaShrot.Peer.b]
Host = 127.0.0.1
Port = 12402
Node = serverB
PublicKey = $($B.Pub)
AcceptTopics = logs
[BakaShrot.Client.b]
PublicKeys = $($B.Pub)
Node = serverB
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Node = kitchen
DefaultTopic = logs
PushTopics = logs;sensors*
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.kitchen2]
PublicKeys = $($K2.Pub)
Node = kitchen-2
DefaultTopic = logs
PushTopics = logs;sensors.temp
[BakaShrot.Client.garage]
PublicKeys = $($G.Pub)
Node = garage
DefaultTopic = logs
; No DefaultTopic: its pushes must name their topic.
[BakaShrot.Client.reader]
PublicKeys = $($R.Pub)
Node = reader
PushTopics = logs
"@
# --- Server B: the old key names, logs = 200, sensors = 201 ----------------
# garage isn't named here (dropped from A), extra isn't named on A (dropped
# from B), node 9 isn't named anywhere (dropped both ways). sensors.temp and
# kitchen-2 aren't named here either, but taken by AcceptTopics/AcceptNodes
# patterns. bsecret is named on both, but held back by SendNodes.
function Write-B([string]$Kitchen) {
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($B.Priv)
NodeId = serverB
[BakaShrot.Topics]
logs = 200
sensors = 201
extra = 202
[BakaShrot.Nodes]
serverA = 1
serverB = 2
kitchen = $Kitchen
blocal = 3
bsecret = 4
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12402
ReplicatingTopicIds = *
DatabasePath = $(Join-Path $Dir "b.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
[BakaShrot.Peer.a]
Host = 127.0.0.1
Port = 12401
NodeId = serverA
PublicKey = $($A.Pub)
AcceptTopics = logs;sensors;sensors.*
AcceptNodes = kitchen;blocal;kitchen-*
SendNodes = blocal;9
[BakaShrot.Client.a]
PublicKeys = $($A.Pub)
Node = serverA
DefaultTopic = logs
; One key, three nodes: a section each.
[BakaShrot.Client.local]
PublicKeys = $($BC.Pub)
Node = blocal
DefaultTopic = sensors
PushTopics = sensors;logs;extra
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.local9]
PublicKeys = $($BC.Pub)
Node = 9
DefaultTopic = logs
PushTopics = sensors;logs;extra
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.localsecret]
PublicKeys = $($BC.Pub)
Node = bsecret
DefaultTopic = logs
PushTopics = sensors;logs;extra
ReadTopics = *
AllowQuery = 1
"@
}
Write-B "7"
# New key names, except garage's (NodeId, by id). No Topic: the server's
# DefaultTopic for each client says where its pushes go.
$ServerKeys = @{ 12401 = $A.Pub; 12402 = $B.Pub }
function Client-Ini($Name, $Keys, $Topic, $Node, $Port, [switch]$OldKeys) {
$P = Join-Path $Dir "$Name.ini"
$NK = "Node"
if ($OldKeys) { $NK = "NodeId" }
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`n$NK = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
$P
}
$Kitchen = Client-Ini "kitchen" $K "logs" "kitchen" 12401
$Garage = Client-Ini "garage" $G "1" "5" 12401 -OldKeys
$Local = Client-Ini "local" $BC "sensors" "blocal" 12402
$Anon = Client-Ini "anon" $BC "logs" "9" 12402
$BSecret = Client-Ini "bsecret" $BC "logs" "bsecret" 12402
$Kitchen2 = Client-Ini "kitchen2" $K2 "logs" "kitchen-2" 12401
$Reader = Client-Ini "reader" $R "logs" "reader" 12401
# reader's key, but kitchen's node: its section only gives it reader.
$Impostor = Client-Ini "impostor" $R "logs" "kitchen" 12401
Set-Content (Join-Path $Dir "m1.json") -Encoding Ascii -Value '{"temp":21}'
Set-Content (Join-Path $Dir "m2.json") -Encoding Ascii -Value '{"temp":22,"where":"kitchen"}'
Set-Content (Join-Path $Dir "m3.json") -Encoding Ascii -Value '{"from":"b-local"}'
$M1 = "@" + (Join-Path $Dir "m1.json"); $M2 = "@" + (Join-Path $Dir "m2.json"); $M3 = "@" + (Join-Path $Dir "m3.json")
$SA = Start-Srv "a"; $SB = Start-Srv "b"
try {
Wait-Port 12401 $SA; Wait-Port 12402 $SB
"--- Server A: pushes and the push filter"
Expect "kitchen pushes into its own topic (logs)" (Tool "BakaShrotPushMessage.exe" @($M1, $Kitchen)) "message #1"
Expect "kitchen pushes into sensors by name" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors", $M2, $Kitchen)) "message #1"
Expect "kitchen pushes into logs by id" (Tool "BakaShrotPushMessage.exe" @("-t", "1", $M2, $Kitchen)) "message #2"
Expect "kitchen can't push into secret" (Tool "BakaShrotPushMessage.exe" @("-t", "secret", $M1, $Kitchen)) "Not allowed to push to topic 'secret'" 1
Expect "unknown topic refused, with its code" (Tool "BakaShrotPushMessage.exe" @("-t", "nope", $M1, $Kitchen)) "\(UnknownName\): Unknown topic 'nope'" 1
Expect "garage (old keys, by ids 1:5) pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M1, $Garage)) "message #1"
Expect "kitchen pushes into sensors.temp (PushTopics sensors*)" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors.temp", $M2, $Kitchen)) "message #1"
Expect "kitchen-2 pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M1, $Kitchen2)) "message #1"
Expect "kitchen-2 pushes into sensors.temp" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors.temp", $M1, $Kitchen2)) "message #1"
Expect "kitchen-2 can't push into sensors" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors", $M1, $Kitchen2)) "Not allowed to push to topic 'sensors'" 1
"--- Server A: identities (a node per key, the default topic the server's)"
Expect "reader (no DefaultTopic) can't push without naming a topic" (Tool "BakaShrotPushMessage.exe" @($M1, $Reader)) "\(NoDefaultTopic\): No default topic for this client" 1
Expect "reader pushes when it names one" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M1, $Reader)) "message #1"
Expect "reader's key can't write as kitchen" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M1, $Impostor)) "Failed to connect and authenticate to [^ ]+ \(AuthRejected\)" 1
"--- Server A: reads and the read filter"
Expect "garage reads logs:kitchen by name" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Garage)) "logs:kitchen#2 \(ids 1:2\)"
Expect "garage reads it by ids, case-insensitive name" (Tool "BakaShrotGetLatestMessage.exe" @("1", "KITCHEN", $Garage)) "logs:kitchen#2"
Expect "garage can't read sensors (default ReadTopics)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Garage)) "Not allowed to read topic 'sensors'" 1
Expect "kitchen reads sensors (ReadTopics = *)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Kitchen)) "sensors:kitchen#1 \(ids 2:2\)"
"--- Server A: resolving and listing"
Expect "kitchen resolves topic sensors" (Tool "BakaShrotResolveIds.exe" @("topic", "sensors", $Kitchen)) "topic sensors = 2"
Expect "kitchen resolves topic id 1" (Tool "BakaShrotResolveIds.exe" @("topic", "1", $Kitchen)) "topic logs = 1"
Expect "kitchen resolves node garage" (Tool "BakaShrotResolveIds.exe" @("node", "garage", $Kitchen)) "node garage = 5"
Expect "garage can't resolve sensors (no access)" (Tool "BakaShrotResolveIds.exe" @("topic", "sensors", $Garage)) "Unknown topic" 1
Expect "kitchen can resolve secret (it may query)" (Tool "BakaShrotResolveIds.exe" @("topic", "secret", $Kitchen)) "topic secret = 3"
Expect "kitchen lists every topic (it may query)" (Tool "BakaShrotList.exe" @("topics", $Kitchen)) "Topics \(4\): \|\s+1 logs\s+config \|\s+2 sensors\s+config \|\s+3 secret\s+config \|\s+4 sensors.temp\s+config"
Expect "garage lists only the topics it can use" (Tool "BakaShrotList.exe" @("topics", $Garage)) "Topics \(1\): \|\s+1 logs"
Expect "the nodes, as JSON" (Tool "BakaShrotList.exe" @("nodes", "--json", $Kitchen)) '(?=.*"kind":"node")(?=.*\{[^}]*"name":"kitchen"[^}]*\})(?=.*\{[^}]*"id":2[,}])'
"--- Server A: queries by name through the view"
Expect "messages view, by names" (Query "SELECT topic, node, message_id FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id" $Kitchen) '\[\["logs","kitchen","1"\],\["logs","kitchen","2"\]\]'
"--- Replication, A -> B, translated (logs 1 -> 200, kitchen 2 -> 7)"
Start-Sleep -Seconds 4
Expect "B has logs:kitchen, under its own ids" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Local)) "logs:kitchen#2 \(ids 200:7\)"
Expect "B has sensors:kitchen" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Local)) "sensors:kitchen#1 \(ids 201:7\)"
Expect "B didn't get logs:garage (garage isn't named on B)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "garage", $Local)) "Unknown node 'garage'" 1
Expect "B took sensors.temp by AcceptTopics sensors.* (new topic id 65535)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors.temp", "kitchen", $Local)) "sensors.temp:kitchen#1 \(ids 65535:7\)"
Expect "B took kitchen-2 by AcceptNodes kitchen-* (new node id 65535)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen-2", $Local)) "logs:kitchen-2#1 \(ids 200:65535\)"
Expect "B: both new ones" (Tool "BakaShrotGetLatestMessage.exe" @("sensors.temp", "kitchen-2", $Local)) "sensors.temp:kitchen-2#1 \(ids 65535:65535\)"
Expect "B: added from the peer, nothing else" (Query "SELECT 'topic', name, topic_id FROM topics WHERE origin = 'peer' UNION ALL SELECT 'node', name, node_id FROM nodes WHERE origin = 'peer'" $Local) '\[\["topic","sensors.temp","65535"\],\["node","kitchen-2","65535"\]\]'
Expect "B's view: same messages by name" (Query "SELECT topic, node, message_id, topic_id, node_id FROM messages WHERE topic = 'sensors'" $Local) '\[\["sensors","kitchen","1","201","7"\]\]'
"--- Replication, B -> A: only what A names and takes (AcceptTopics = logs)"
Expect "B's local pushes into sensors" (Tool "BakaShrotPushMessage.exe" @($M3, $Local)) "message #1"
Expect "B's local pushes into logs" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M3, $Local)) "message #1"
Expect "B's local pushes into extra" (Tool "BakaShrotPushMessage.exe" @("-t", "extra", $M3, $Local)) "message #1"
Expect "B's unnamed node 9 pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M3, $Anon)) "message #1"
Expect "B's bsecret pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M3, $BSecret)) "message #1"
Start-Sleep -Seconds 4
Expect "A got logs:blocal (ids 1:20)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "blocal", $Kitchen)) 'logs:blocal#1 \(ids 1:20\), pushed \d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \| \{"from":"b-local"\}'
Expect "A didn't get sensors:blocal (not accepted)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "blocal", $Kitchen)) "No message" 1
Expect "A didn't get logs:9 (unnamed)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "9", $Kitchen)) "No message" 1
Expect "A didn't get logs:bsecret (B's SendNodes)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "bsecret", $Kitchen)) "No message" 1
Expect "A's pairs, nothing more, nothing twice" (Query "SELECT topic, node, COUNT(*) FROM messages GROUP BY 1, 2 ORDER BY 1, 2" $Kitchen) '\[\["logs","blocal","1"\],\["logs","garage","1"\],\["logs","kitchen","2"\],\["logs","kitchen-2","1"\],\["logs","reader","1"\],\["sensors","kitchen","1"\],\["sensors.temp","kitchen","1"\],\["sensors.temp","kitchen-2","1"\]\]'
} finally {
Stop-Srv $SA; Stop-Srv $SB
}
"--- No refusals: each side only sent what the other one knows"
$Refusals = @(Get-Content (Join-Path $Dir "a.log"), (Join-Path $Dir "b.log") | Select-String "replicated here|known here|refused:")
$Ok = $Refusals.Count -eq 0
if (-not $Ok) { $Fails++ }
"{0} no replication refusals in either log`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $(if ($Ok) { "none" } else { $Refusals -join " | " })
$Ok = (Get-Content (Join-Path $Dir "a.log") -Raw) -match "isn't allowed to write as node kitchen with its public key"
if (-not $Ok) { $Fails++ }
"{0} A logged why the impostor was refused" -f $(if ($Ok) { "PASS" } else { "FAIL" })
"A:"; Get-Content (Join-Path $Dir "a.log") | Select-String "\[Peer\] Sent|Names" | % { " $_" }
"B:"; Get-Content (Join-Path $Dir "b.log") | Select-String "\[Peer\] Sent|Names" | % { " $_" }
"--- Conflict: B's config now says kitchen = 8, but its messages are under 7"
Write-B "8"
$SB = Start-Srv "b"
$SB.P.WaitForExit(15000) | Out-Null
$Log = Get-Content (Join-Path $Dir "b.log") -Raw
$Ok = $SB.P.HasExited -and $SB.P.ExitCode -eq 1 -and $Log -match "give it id 7"
if (-not $Ok) { $Fails++ }
"{0} B refuses to start`n -> [{1}] {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $SB.P.ExitCode, (($Log -split "`n") | Select-String "names don't match")
if (-not $SB.P.HasExited) { Stop-Srv $SB }
"--- Conflict fixed: kitchen = 7 again"
Write-B "7"
$SB = Start-Srv "b"
try {
Wait-Port 12402 $SB
Expect "B starts, kitchen still 7" (Tool "BakaShrotList.exe" @("nodes", $Local)) "\s+7 kitchen\s+config"
} finally { Stop-Srv $SB }
"--- The old Identities (before protocol 5): refused at start, saying what to write"
(Get-Content (Join-Path $Dir "a.ini") -Raw) -replace "Node = garage\r?\nDefaultTopic = logs", "Identities = logs:garage" | Set-Content (Join-Path $Dir "old.ini") -Encoding Ascii
$SO = Start-Srv "old"
$Exited = $SO.P.WaitForExit(10000)
if (-not $Exited) { Stop-Srv $SO }
$Log = Get-Content (Join-Path $Dir "old.log") -Raw
$Ok = $Exited -and $SO.P.ExitCode -ne 0 -and $Log -match "write Node = garage and DefaultTopic = logs instead of Identities = logs:garage"
if (-not $Ok) { $Fails++ }
"{0} refused, with what to write instead`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), (($Log -split "`n") | Select-String "Identities" | Select-Object -First 1)
# --- C and D: topics listed without ids, no nodes listed at all ------------
# The servers pick the ids, the nodes come from the sections (C's own, its
# peer's, its client's), D takes the client's node from C as it comes.
$C = New-KeyPair; $D = New-KeyPair; $KC = New-KeyPair
# LF line endings on purpose: the names sections are read by hand, the
# Preferences library misreads a bare name there (Config.pbi).
function Write-C([string]$Topics, [string]$Sync = "NORMAL") {
$Text = @"
[BakaShrot]
PrivateKey = $($C.Priv)
Node = serverC
[BakaShrot.Topics]
$Topics
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12401
ReplicatingTopics = logs
DatabasePath = $(Join-Path $Dir "c.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
Synchronous = $Sync
[BakaShrot.Peer.d]
Host = 127.0.0.1
Port = 12402
Node = serverD
PublicKey = $($D.Pub)
[BakaShrot.Client.d]
PublicKeys = $($D.Pub)
Node = serverD
AllowWrite = 0
[BakaShrot.Client.kitchen]
PublicKeys = $($KC.Pub)
Node = kitchen
DefaultTopic = logs
ReadTopics = *
"@
[IO.File]::WriteAllText((Join-Path $Dir "c.ini"), ($Text -replace "`r`n", "`n"))
}
Write-C "logs`nsensors"
Set-Content (Join-Path $Dir "d.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($D.Priv)
Node = serverD
[BakaShrot.Topics]
logs
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12402
ReplicatingTopics = logs
DatabasePath = $(Join-Path $Dir "d.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
[BakaShrot.Peer.c]
Host = 127.0.0.1
Port = 12401
Node = serverC
PublicKey = $($C.Pub)
[BakaShrot.Client.c]
PublicKeys = $($C.Pub)
Node = serverC
AllowWrite = 0
[BakaShrot.Client.watcher]
PublicKeys = $($KC.Pub)
Node = watcher
ReadTopics = *
"@
$ServerKeys[12401] = $C.Pub; $ServerKeys[12402] = $D.Pub
$KitchenC = Client-Ini "kitchen-c" $KC "logs" "kitchen" 12401
$Watcher = Client-Ini "watcher" $KC "logs" "watcher" 12402
"--- C and D: names without ids"
$SC = Start-Srv "c"; $SD = Start-Srv "d"
try {
Wait-Port 12401 $SC; Wait-Port 12402 $SD
Expect "C gives the listed topics ids, in order" (Tool "BakaShrotList.exe" @("topics", $KitchenC)) "\s1 logs\s+config.*\s2 sensors\s+config"
Expect "C names its own, its peer's and its client's nodes" (Tool "BakaShrotList.exe" @("nodes", $KitchenC)) "\s1 serverC\s+config.*\s2 serverD\s+config.*\s3 kitchen\s+config"
Expect "kitchen pushes to its DefaultTopic" (Tool "BakaShrotPushMessage.exe" @($M1, $KitchenC)) "message #1"
$Deadline = (Get-Date).AddSeconds(15)
do {
$R = Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Watcher)
if ($R.Code -eq 0) { break }
Start-Sleep -Milliseconds 300
} while ((Get-Date) -lt $Deadline)
Expect "D took logs:kitchen though it never named kitchen (AcceptNodes = * by default)" $R "logs:kitchen#1 \(ids 1:65535\)"
} finally {
Stop-Srv $SC; Stop-Srv $SD
}
"--- C again, its topics reordered and a new one first: the ids stay"
Write-C "alpha`nsensors`nlogs"
$SC = Start-Srv "c"
try {
Wait-Port 12401 $SC
Expect "logs and sensors keep 1 and 2, alpha gets 3" (Tool "BakaShrotList.exe" @("topics", $KitchenC)) "\s1 logs\s+config.*\s2 sensors\s+config.*\s3 alpha\s+config"
Expect "kitchen's message still under logs" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $KitchenC)) "logs:kitchen#1 \(ids 1:3\)"
} finally { Stop-Srv $SC }
"--- Synchronous: C ran with NORMAL, D with the default FULL, OFF is refused"
$Ok = ((Get-Content (Join-Path $Dir "c.log") -Raw) -match "is ready \(synchronous NORMAL\)") -and ((Get-Content (Join-Path $Dir "d.log") -Raw) -match "is ready \(synchronous FULL\)")
if (-not $Ok) { $Fails++ }
"{0} C logged NORMAL, D FULL" -f $(if ($Ok) { "PASS" } else { "FAIL" })
Write-C "logs" "OFF"
$SO = Start-Srv "c"
$Exited = $SO.P.WaitForExit(10000)
if (-not $Exited) { Stop-Srv $SO }
$Log = Get-Content (Join-Path $Dir "c.log") -Raw
$Ok = $Exited -and $SO.P.ExitCode -ne 0 -and $Log -match "Synchronous = OFF isn't allowed"
if (-not $Ok) { $Fails++ }
"{0} Synchronous = OFF refused at start`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), (($Log -split "`n") | Select-String "Synchronous" | Select-Object -First 1)
"--- browse / browse_messages, as a database tool uses them (C stopped)"
$PythonExe = Get-Command python -ErrorAction SilentlyContinue
if ($PythonExe) {
Set-Content (Join-Path $Dir "browse.py") -Encoding Ascii -Value @'
import sqlite3, sys
db = sqlite3.connect(sys.argv[1])
db.execute("PRAGMA foreign_keys = ON") # like SQLiteStudio
print("rows", db.execute("SELECT COUNT(*) FROM browse").fetchone()[0])
db.execute("UPDATE browse SET topic = 'logs', node = NULL"); db.commit()
print("logs", db.execute("SELECT node, message_id, attachment_size FROM browse_messages").fetchall())
db.execute("UPDATE browse SET topic = 'LOGS', node = 'kitchen'"); db.commit()
print("kitchen", db.execute("SELECT node, message_id FROM browse_messages").fetchall())
try:
db.execute("UPDATE browse SET topic = 'nope'"); db.commit(); print("bad accepted")
except sqlite3.IntegrityError:
print("bad refused")
db.execute("UPDATE browse SET topic = 'sensors', node = NULL"); db.commit()
print("sensors", db.execute("SELECT COUNT(*) FROM browse_messages").fetchone()[0])
'@
$Out = (& $PythonExe.Source -B (Join-Path $Dir "browse.py") (Join-Path $Dir "c.sqlite") 2>&1) -join " | "
$Ok = $Out -eq "rows 1 | logs [('kitchen', 1, None)] | kitchen [('kitchen', 1)] | bad refused | sensors 0"
if (-not $Ok) { $Fails++ }
"{0} one row, a topic shows its messages, a node narrows them, an unknown topic is refused`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $Out
} else {
"SKIP browse: no python on the PATH"
}
""
if ($Fails -eq 0) { "ALL PASSED" } else { "$Fails FAILED"; exit 1 }
+119
View File
@@ -0,0 +1,119 @@
# End-to-end test of the Python interactor (Interactors/Python/bakashrot.py):
# starts a server with an empty database and runs
# Interactors/Python/check_bakashrot.py against it, through Build\'s DLL,
# then Tests/wire_check.py: what goes over the wire is encrypted.
# Needs Build\ (Build.ps1), Build\Bench\BenchServer.exe (Bench-Replication.ps1,
# or compile Tests\Bench\BenchServer.pb into it) and a 64-bit Python 3.8+.
# Uses ports 12406 and 12407.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\Python-Test.ps1 [-Python <python.exe>]
param(
[string]$Build = (Join-Path $PSScriptRoot "..\Build"),
[string]$Python = "python"
)
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_pythontest"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Port = 12406
$ProxyPort = 12407
function New-KeyPair {
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
$C = New-Object System.Net.Sockets.TcpClient
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
}
$S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair
Set-Content (Join-Path $Dir "server.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($S.Priv)
Node = server
[BakaShrot.Topics]
logs = 1
secret = 2
[BakaShrot.Nodes]
server = 1
kitchen = 5
lounge = 6
[BakaShrot.Server]
Host = 127.0.0.1
Port = $Port
DatabasePath = $(Join-Path $Dir "server.sqlite")
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Node = kitchen
DefaultTopic = logs
PushTopics = logs;secret
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.lounge]
PublicKeys = $($L.Pub)
Node = lounge
DefaultTopic = logs
ReadTopics = logs
"@
function Client-Ini($Name, $Keys) {
$P = Join-Path $Dir "$Name.ini"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)"
$P
}
$Kitchen = Client-Ini "kitchen" $K
$Lounge = Client-Ini "lounge" $L
if (Test-Port $Port) { throw "Port $Port is already in use" }
$Stop = Join-Path $Dir "server.stop"
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "server.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput (Join-Path $Dir "server.log") -WindowStyle Hidden -PassThru
$null = $P.Handle
$Code = 1
try {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($P.HasExited) { throw "The server exited: $(Get-Content (Join-Path $Dir "server.log") -Raw)" }
if ((Get-Date) -gt $D) { throw "The server isn't listening" }
Start-Sleep -Milliseconds 100
}
$env:PYTHONIOENCODING = "utf-8"
& $Python (Join-Path $PSScriptRoot "..\Interactors\Python\check_bakashrot.py") (Join-Path $Build "BakaShrot_Client.dll") $Kitchen $Lounge
$Code = $LASTEXITCODE
# Refusals are expected (the checks ask for them), their codes' names
# (QueryFailed, InvalidRequest) aren't problems.
$Bad = @(Get-Content (Join-Path $Dir "server.log") | Where-Object { $_ -notmatch "Refused a request" -and $_ -match "invalid|unexpected|Failed|decrypt|sealed" })
if ($Bad.Count) { "FAIL Server log: $($Bad -join ' / ')"; $Code = 1 } else { "PASS Server log: no invalid or unexpected packets" }
# The wire: encrypted, tampering and a wrong server key refused. Another
# key pair's public key plays the wrong server's.
""
& $Python -B (Join-Path $PSScriptRoot "wire_check.py") (Join-Path $Build "BakaShrot_Client.dll") $Kitchen $ProxyPort $L.Pub
if ($LASTEXITCODE) { $Code = 1 }
Start-Sleep -Milliseconds 300
$Log = Get-Content (Join-Path $Dir "server.log")
$Checks = [ordered]@{
"Server log: the tampered packet didn't decrypt" = "sent a packet that doesn't decrypt"
"Server log: the hello for another server wasn't opened" = "hello that isn't sealed for this server"
}
foreach ($Name in $Checks.Keys) {
if (@($Log | Where-Object { $_ -match [regex]::Escape($Checks[$Name]) }).Count) { "PASS $Name" } else { "FAIL $Name"; $Code = 1 }
}
}
finally {
if (-not $P.HasExited) {
Set-Content $Stop "x"
if (-not $P.WaitForExit(15000)) { Stop-Process -Id $P.Id -Force }
}
}
exit $Code
+280
View File
@@ -0,0 +1,280 @@
# End-to-end test of a server killed mid-traffic and restarted (a crash,
# not a clean stop): what it acknowledged survives, its ids carry on where
# they stopped, and the two servers catch up with each other both ways.
#
# Two linked servers, A and B, each with its own client node pushing
# (kitchen on A, garage on B: one writer per topic/node pair) through
# Tests/restart_pusher.py, as fast as acknowledgements come back:
# 1. B killed while both push; A keeps pushing while B is down; B
# restarted: every push it acknowledged is there, no gap, its next id
# follows, and both servers end up with the same messages.
# 2. B killed again a fraction of a second into that catch-up, restarted:
# still converges.
# 3. A killed while both push (the other direction), restarted: same.
# The servers are killed with Stop-Process -Force (TerminateProcess), like
# a crash. Synchronous is the default (FULL); a killed process loses
# nothing committed with NORMAL either, only a power loss would.
#
# Needs Build\ (Build.ps1), Build\Bench\BenchServer.exe, and Python 3 on the
# PATH (the pushers use Interactors/Python/bakashrot.py). Uses ports
# 12415-12416.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\Restart-Test.ps1
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"), [string]$Python = "python")
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_restarttest"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Dll = Join-Path $Build "BakaShrot_Client.dll"
$Pusher = Join-Path $PSScriptRoot "restart_pusher.py"
$Fails = 0
$PythonExe = (Get-Command $Python -ErrorAction SilentlyContinue)
if (-not $PythonExe) { "FAIL no Python ($Python), the pushers need it"; exit 1 }
$PythonExe = $PythonExe.Source
function New-KeyPair {
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
$C = New-Object System.Net.Sockets.TcpClient
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
}
function Tool([string]$Name, [string[]]$A) {
$O = & (Join-Path $Build $Name) @A 2>&1
@{ Code = $LASTEXITCODE; Out = ($O -join " | ") }
}
function Check([string]$What, [bool]$Ok, [string]$Detail) {
if (-not $Ok) { $script:Fails++ }
"{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail
}
function Start-Srv($Name) {
$Stop = Join-Path $Dir "$Name.stop"
Remove-Item $Stop -ErrorAction SilentlyContinue
# Each run its own log, the previous ones are kept for a look.
$script:Runs[$Name] = 1 + [int]$script:Runs[$Name]
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput (Join-Path $Dir ("{0}.{1}.log" -f $Name, $script:Runs[$Name])) -WindowStyle Hidden -PassThru
$null = $P.Handle
@{ P = $P; Stop = $Stop; Name = $Name }
}
function Stop-Srv($S) {
if ($S.P.HasExited) { return }
Set-Content $S.Stop "x"
if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force }
}
function Kill-Srv($S) {
Stop-Process -Id $S.P.Id -Force
$null = $S.P.WaitForExit(10000)
}
function Wait-Port($Port, $S) {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($S.P.HasExited) { throw "$($S.Name) exited" }
if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" }
Start-Sleep -Milliseconds 100
}
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir ("q-" + [guid]::NewGuid().ToString("N") + ".sql"); Set-Content $F -Encoding Ascii -Value $Sql
$R = Tool "BakaShrotQuery.exe" @("@$F", $Ini)
Remove-Item $F
$R
}
# A pusher in the background: Name's out file gets "<id> <seq>" per
# acknowledged push, then STOPPED or ERR.
function Start-Pusher($Name, $Ini) {
$Out = Join-Path $Dir "$Name.out"; $Stop = Join-Path $Dir "$Name.stop"
Remove-Item $Out, $Stop -ErrorAction SilentlyContinue
$P = Start-Process -FilePath $PythonExe -ArgumentList "-B", "`"$Pusher`"", "`"$Dll`"", "`"$Ini`"", "`"$Stop`"", "`"$Out`"", $Name `
-WorkingDirectory $Build -WindowStyle Hidden -PassThru
$null = $P.Handle
@{ P = $P; Out = $Out; Stop = $Stop; Name = $Name }
}
function Stop-Pusher($Pu) {
Set-Content $Pu.Stop "x"
if (-not $Pu.P.WaitForExit(15000)) { Stop-Process -Id $Pu.P.Id -Force }
}
# What a pusher saw: how many acknowledged, the last id and seq, how it ended.
function Read-Pusher($Pu) {
$Lines = @(Get-Content $Pu.Out -ErrorAction SilentlyContinue)
$Acked = @($Lines | Where-Object { $_ -match "^\d+ \d+$" })
$Last = if ($Acked.Count) { $Acked[-1] -split " " } else { @("0", "0") }
@{ Count = $Acked.Count; LastId = [int64]$Last[0]; LastSeq = [int]$Last[1]; End = [string]($Lines | Select-Object -Last 1) }
}
# Every node of logs on a server: count, first and last id, and sums over
# the data and the push times, to compare two servers.
$StatsSql = "SELECT node, COUNT(*), MIN(message_id), MAX(message_id), SUM(length(message_data)), SUM(pushed_at % 1000003), SUM(message_id * length(message_data)) FROM messages WHERE topic = 'logs' GROUP BY node ORDER BY node"
function Stats($Ini) {
$R = Query $StatsSql $Ini
if ($R.Code -ne 0) { return "query failed: " + $R.Out }
($R.Out -replace '^.*"rows":', '')
}
# The highest id and the count of a node on a server.
function Head($Node, $Ini) {
$R = Query "SELECT COUNT(*), COALESCE(MAX(message_id), 0) FROM messages WHERE topic = 'logs' AND node = '$Node'" $Ini
if ($R.Out -match '\[\["(\d+)","(\d+)"\]\]') { @{ Count = [int64]$Matches[1]; Max = [int64]$Matches[2] } } else { @{ Count = -1; Max = -1; Out = $R.Out } }
}
# Waits until A and B have the same messages, and at least Kitchen and
# Garage messages of each node. Returns the stats, and whether they matched.
function Wait-Converged($Kitchen, $Garage, $Seconds = 60) {
$D = (Get-Date).AddSeconds($Seconds)
do {
$SA = Stats $OnA; $SB = Stats $OnB
$HK = Head "kitchen" $OnB; $HG = Head "garage" $OnA
if ($SA -eq $SB -and $HK.Count -ge $Kitchen -and $HG.Count -ge $Garage) { return @{ Ok = $true; A = $SA; B = $SB } }
Start-Sleep -Milliseconds 250
} while ((Get-Date) -lt $D)
@{ Ok = $false; A = $SA; B = $SB }
}
# What a restarted server must show for the node its pusher wrote to: every
# acknowledged push there (ids 1..max without a gap, max at least the last
# acknowledged one, its data the one acknowledged), and at most one more
# (committed, the answer lost with the kill). Leaves the node's head in
# $Survived: a function's return value would take its PASS/FAIL lines too.
function Check-Survived($What, $Node, $Pu, $Ini) {
$Seen = Read-Pusher $Pu
$H = Head $Node $Ini
Check "$What`: every acknowledged push survived, ids without a gap" `
($Seen.LastId -gt 0 -and $H.Count -eq $H.Max -and $H.Max -ge $Seen.LastId -and $H.Max -le $Seen.LastId + 1) `
("{0} acknowledged, last #{1}; stored {2}, last #{3}; pusher: {4}" -f $Seen.Count, $Seen.LastId, $H.Count, $H.Max, $Seen.End)
$R = Query "SELECT message_data FROM messages WHERE topic = 'logs' AND node = '$Node' AND message_id = $($Seen.LastId)" $Ini
Check "$What`: the last acknowledged one is the one pushed" ($R.Out -match ('\\"seq\\":' + $Seen.LastSeq + '[,}]')) $R.Out
$script:Survived = $H
}
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair
$Runs = @{}
# Topics listed by name, nodes from the sections: a restart must give every
# name its id back, by the database.
function Write-Config($Name, $Keys, $Port, $Node, $PeerName, $PeerPort, $PeerNode, $PeerKey, $ClientNode, $ClientKey) {
Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($Keys.Priv)
Node = $Node
[BakaShrot.Topics]
logs
[BakaShrot.Server]
Host = 127.0.0.1
Port = $Port
ReplicatingTopics = logs
DatabasePath = $(Join-Path $Dir "$Name.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
PeerBatchSize = 10
[BakaShrot.Peer.$PeerName]
Host = 127.0.0.1
Port = $PeerPort
Node = $PeerNode
PublicKey = $PeerKey
[BakaShrot.Client.$PeerName]
PublicKeys = $PeerKey
Node = $PeerNode
AllowWrite = 0
[BakaShrot.Client.$ClientNode]
PublicKeys = $ClientKey
Node = $ClientNode
DefaultTopic = logs
ReadTopics = *
AllowQuery = 1
"@
}
Write-Config "a" $A 12415 "serverA" "b" 12416 "serverB" $B.Pub "kitchen" $K.Pub
Write-Config "b" $B 12416 "serverB" "a" 12415 "serverA" $A.Pub "garage" $G.Pub
Set-Content (Join-Path $Dir "kitchen.ini") -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = 12415`r`nServerPublicKey = $($A.Pub)"
Set-Content (Join-Path $Dir "garage.ini") -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($G.Priv)`r`nPublicKey = $($G.Pub)`r`nNode = garage`r`nServerHost = 127.0.0.1`r`nServerPort = 12416`r`nServerPublicKey = $($B.Pub)"
$OnA = Join-Path $Dir "kitchen.ini"; $OnB = Join-Path $Dir "garage.ini"
Set-Content (Join-Path $Dir "next.json") -Encoding Ascii -Value '{"after":"restart"}'
$Next = "@" + (Join-Path $Dir "next.json")
$SA = Start-Srv "a"; $SB = Start-Srv "b"
$Pushers = @()
try {
Wait-Port 12415 $SA; Wait-Port 12416 $SB
"--- 1. B killed while both push, A keeps pushing, B restarted"
$PK = Start-Pusher "kitchen-1" $OnA; $PG = Start-Pusher "garage-1" $OnB; $Pushers += $PK, $PG
Start-Sleep -Seconds 3
Kill-Srv $SB
$null = $PG.P.WaitForExit(15000)
Start-Sleep -Seconds 3 # A goes on alone
Stop-Pusher $PK
$KSeen = Read-Pusher $PK
# 104 (ConnectionLost) if killed during a push, 100 (NotConnected) if
# between two: the next push finds the connection already gone.
Check "the garage pusher noticed B was gone: ConnectionLostError, code 104 or 100" ($PG.P.HasExited -and (Read-Pusher $PG).End -match "^ERR 10[04] ConnectionLostError") (Read-Pusher $PG).End
Check "kitchen kept pushing on A meanwhile" ($KSeen.Count -gt 100 -and $KSeen.End -eq "STOPPED") ("{0} acknowledged" -f $KSeen.Count)
$SB = Start-Srv "b"; Wait-Port 12416 $SB
Check-Survived "B" "garage" $PG $OnB
$HG = $Survived
$R = Tool "BakaShrotPushMessage.exe" @($Next, $OnB)
Check "B: the next push carries on from the last id" ($R.Out -match "message #$($HG.Max + 1)\b") ("after #{0}: {1}" -f $HG.Max, $R.Out)
$C = Wait-Converged $KSeen.LastId ($HG.Max + 1)
Check "A and B converged (B caught up on kitchen, A on garage)" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B)
"--- 2. B killed again in the middle of its catch-up"
$Before = (Head "kitchen" $OnB).Count
$PK = Start-Pusher "kitchen-2" $OnA; $Pushers += $PK
Start-Sleep -Seconds 1
Kill-Srv $SB
Start-Sleep -Seconds 6 # a backlog for B
Stop-Pusher $PK
$Total = (Head "kitchen" $OnA).Max
$SB = Start-Srv "b"; Wait-Port 12416 $SB
# Killed as soon as some of the backlog is in, not all of it.
$D = (Get-Date).AddSeconds(30)
do {
$Mid = Head "kitchen" $OnB
if ($Mid.Count -gt $Before -and $Mid.Count -lt $Total) { Kill-Srv $SB; break }
Start-Sleep -Milliseconds 20
} while ($Mid.Count -lt $Total -and (Get-Date) -lt $D)
Check "B killed partway through its catch-up" ($Mid.Count -gt $Before -and $Mid.Count -lt $Total) `
("B had {0} kitchen messages before, {1} when killed, A {2}" -f $Before, $Mid.Count, $Total)
if (-not $SB.P.HasExited) { Kill-Srv $SB }
$SB = Start-Srv "b"; Wait-Port 12416 $SB
$C = Wait-Converged $Total 0
Check "B restarted, still converged" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B)
$H = Head "kitchen" $OnB
Check "B's copy of kitchen has no gap" ($H.Count -eq $H.Max -and $H.Max -eq $Total) ("{0} stored, last #{1}, A's last #{2}" -f $H.Count, $H.Max, $Total)
"--- 3. A killed while both push, B keeps pushing, A restarted"
$PK = Start-Pusher "kitchen-3" $OnA; $PG = Start-Pusher "garage-3" $OnB; $Pushers += $PK, $PG
Start-Sleep -Seconds 3
Kill-Srv $SA
$null = $PK.P.WaitForExit(15000)
Start-Sleep -Seconds 3 # B goes on alone
Stop-Pusher $PG
$GSeen = Read-Pusher $PG
Check "the kitchen pusher noticed A was gone: ConnectionLostError, code 104 or 100" ($PK.P.HasExited -and (Read-Pusher $PK).End -match "^ERR 10[04] ConnectionLostError") (Read-Pusher $PK).End
$SA = Start-Srv "a"; Wait-Port 12415 $SA
Check-Survived "A" "kitchen" $PK $OnA
$HK = $Survived
$R = Tool "BakaShrotPushMessage.exe" @($Next, $OnA)
Check "A: the next push carries on from the last id" ($R.Out -match "message #$($HK.Max + 1)\b") ("after #{0}: {1}" -f $HK.Max, $R.Out)
$C = Wait-Converged ($HK.Max + 1) $GSeen.LastId
Check "A and B converged again" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B)
"--- Logs"
$Bad = @(Get-ChildItem $Dir -Filter "*.log" | Select-String "Failed|refused|corrupt|malformed" | Where-Object { $_.Line -notmatch "Failed to connect|Lost the link|link to .* failed" })
Check "no failure in either server's logs, other than the links lost to the kills" ($Bad.Count -eq 0) $(if ($Bad.Count) { ($Bad | Select-Object -First 5 | ForEach-Object { "$($_.Filename): $($_.Line)" }) -join " | " } else { "none" })
} finally {
foreach ($Pu in $Pushers) { if (-not $Pu.P.HasExited) { Stop-Process -Id $Pu.P.Id -Force } }
Stop-Srv $SA; Stop-Srv $SB
}
""
if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" }
+353
View File
@@ -0,0 +1,353 @@
# End-to-end test of pushed_at and [BakaShrot.Retention]:
# - a database from before pushed_at gets it (the time of the upgrade), and
# its ids go on;
# - a push is stamped with the time it arrived (UTC), BakaShrotGetMessages
# --time and BakaShrotGetLatestMessage show it, replication carries it as is;
# - each server deletes a topic's messages past its own max age (by name,
# by pattern, "*"), only its own: the peer keeps its copies;
# - after deleting, ids go on, and the peer doesn't send them again;
# - what a peer replicates already past the max age isn't stored, but
# counts as received: not sent again;
# - an age without a unit is refused at start.
# Two linked servers, A (port 12408) and B (12409).
# Needs Build\ (Build.ps1), Build\Bench\BenchServer.exe (or compile
# Tests\Bench\BenchServer.pb into it), and Python 3 for the old database
# (skipped without it).
# Usage: powershell -ExecutionPolicy Bypass -File Tests\Retention-Test.ps1 [-Python <python.exe>]
param(
[string]$Build = (Join-Path $PSScriptRoot "..\Build"),
[string]$Python = "python"
)
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_retentiontest"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Fails = 0
function New-KeyPair {
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
$C = New-Object System.Net.Sockets.TcpClient
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
}
function Tool([string]$Name, [string[]]$A) {
$O = & (Join-Path $Build $Name) @A 2>&1
@{ Code = $LASTEXITCODE; Out = ($O -join " | "); Lines = @($O | Where-Object { "$_" -ne "" }) }
}
function Check([string]$What, [bool]$Ok, [string]$Detail) {
if (-not $Ok) { $script:Fails++ }
"{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail
}
function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) {
Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out)
}
function Start-Srv($Name) {
$Stop = Join-Path $Dir "$Name.stop"
Remove-Item $Stop -ErrorAction SilentlyContinue
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput (Join-Path $Dir "$Name.log") -WindowStyle Hidden -PassThru
$null = $P.Handle
@{ P = $P; Stop = $Stop; Name = $Name }
}
function Stop-Srv($S) {
if ($S.P.HasExited) { return }
Set-Content $S.Stop "x"
if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force }
}
function Wait-Port($Port, $S) {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content (Join-Path $Dir "$($S.Name).log") -Raw)" }
if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" }
Start-Sleep -Milliseconds 100
}
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
}
# Waits until Sql answers something matching Pattern, for up to Seconds.
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
$D = (Get-Date).AddSeconds($Seconds)
do {
$R = Query $Sql $Ini
if ($R.Code -eq 0 -and $R.Out -match $Pattern) { return $R }
Start-Sleep -Milliseconds 250
} while ((Get-Date) -lt $D)
$R
}
function Count($Topic, $Where = "") {
"SELECT COUNT(*) AS n FROM messages WHERE topic = '$Topic' AND node = 'kitchen' $Where"
}
function NowMs { [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() }
# Pushes Data from a file (PowerShell 5 strips the quotes of an argument).
function Push($Data, $Ini, [string]$Topic = "") {
$F = Join-Path $Dir "push.txt"
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
$A = @()
if ($Topic) { $A += @("-t", $Topic) }
Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini))
}
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair
# A: short is kept 3 s here, everything else forever. Checked every second.
Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($A.Priv)
Node = serverA
[BakaShrot.Topics]
logs = 1
short = 2
keep = 3
late = 4
[BakaShrot.Nodes]
serverA = 10
serverB = 11
kitchen = 2
[BakaShrot.Retention]
short = 3s
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12408
ReplicatingTopics = logs;short;keep;late
DatabasePath = $(Join-Path $Dir "a.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
RetentionInterval = 1
[BakaShrot.Peer.b]
Host = 127.0.0.1
Port = 12409
Node = serverB
PublicKey = $($B.Pub)
[BakaShrot.Client.b]
PublicKeys = $($B.Pub)
Node = serverB
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Node = kitchen
DefaultTopic = logs
PushTopics = logs;short;keep;late
ReadTopics = *
AllowQuery = 1
"@
# B: other ids. short forever, keep by a pattern (4 s), the rest 1 h.
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($B.Priv)
Node = serverB
[BakaShrot.Topics]
logs = 300
short = 301
keep = 302
late = 303
[BakaShrot.Nodes]
serverA = 1
serverB = 2
kitchen = 30
[BakaShrot.Retention]
short = forever
ke* = 4s
late = 3s
* = 1h
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12409
ReplicatingTopics = logs;short;keep;late
DatabasePath = $(Join-Path $Dir "b.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
RetentionInterval = 1
[BakaShrot.Peer.a]
Host = 127.0.0.1
Port = 12408
Node = serverA
PublicKey = $($A.Pub)
[BakaShrot.Client.a]
PublicKeys = $($A.Pub)
Node = serverA
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Node = kitchen
DefaultTopic = logs
ReadTopics = *
AllowQuery = 1
"@
$ServerKeys = @{ 12408 = $A.Pub; 12409 = $B.Pub }
function Client-Ini($Name, $Port) {
$P = Join-Path $Dir "$Name.ini"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
$P
}
$OnA = Client-Ini "kitchen-a" 12408
$OnB = Client-Ini "kitchen-b" 12409
# A database from before pushed_at, for A: one message, logs:kitchen #1.
$HasOld = $false
$Seed = @"
import sqlite3, sys
db = sqlite3.connect(sys.argv[1])
db.execute("CREATE TABLE data (topic_id INTEGER NOT NULL, node_id INTEGER NOT NULL, message_id INTEGER NOT NULL, message_data TEXT NOT NULL, is_json INTEGER NOT NULL GENERATED ALWAYS AS (json_valid(message_data)) STORED, UNIQUE (topic_id, node_id, message_id))")
db.execute("INSERT INTO data (topic_id, node_id, message_id, message_data) VALUES (1, 2, 1, '{\"old\":1}')")
db.commit()
"@
Set-Content (Join-Path $Dir "seed.py") -Encoding Ascii -Value $Seed
try {
& $Python -B (Join-Path $Dir "seed.py") (Join-Path $Dir "a.sqlite") 2>&1 | Out-Null
$HasOld = ($LASTEXITCODE -eq 0)
} catch { $HasOld = $false }
if (-not $HasOld) { "SKIP the old database: no Python ($Python)" ; Remove-Item (Join-Path $Dir "a.sqlite") -ErrorAction SilentlyContinue }
foreach ($Port in 12408, 12409) { if (Test-Port $Port) { throw "Port $Port is already in use" } }
$Before = NowMs
$SA = Start-Srv "a"; $SB = $null
try {
Wait-Port 12408 $SA
"--- Before B starts: late #1-#2 on A, past B's 3 s once B gets them"
foreach ($i in 1..2) { Expect "push late #$i" (Push "{`"late`":$i}" $OnA "late") "message #$i" }
Start-Sleep -Seconds 5
$SB = Start-Srv "b"
Wait-Port 12409 $SB
Start-Sleep -Seconds 2
"--- The old database"
if ($HasOld) {
$R = Query "SELECT message_id, pushed_at FROM data WHERE topic_id = 1 AND node_id = 2" $OnA
$Stamp = 0; if ($R.Out -match '\[\["1","(\d+)"\]\]') { $Stamp = [int64]$Matches[1] }
Check "the old message got pushed_at: the time of the upgrade" ($Stamp -ge $Before - 1000 -and $Stamp -le (NowMs)) $R.Out
Expect "its ids go on: the next push is #2" (Push '{"n":"after upgrade"}' $OnA) "message #2"
} else {
Expect "first push" (Push '{"n":"first"}' $OnA) "message #1"
Expect "second push" (Push '{"n":"after upgrade"}' $OnA) "message #2"
}
"--- pushed_at"
$PushedFrom = NowMs
Expect "push logs #3" (Push '{"n":"stamped"}' $OnA) "message #3"
$PushedTo = NowMs
$R = Query "SELECT pushed_at, pushed_utc FROM messages WHERE topic = 'logs' AND node = 'kitchen' AND message_id = 3" $OnA
$Stamp = 0; if ($R.Out -match '\[\["(\d+)","([^"]+)"\]\]') { $Stamp = [int64]$Matches[1]; $Utc = $Matches[2] }
Check "stamped with the time it arrived, in UTC ms" ($Stamp -ge $PushedFrom - 50 -and $Stamp -le $PushedTo + 50) "$Stamp in [$PushedFrom, $PushedTo]"
$Expected = [DateTimeOffset]::FromUnixTimeMilliseconds($Stamp).UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
Check "the view's pushed_utc is the same, as text" ($Utc -eq $Expected) "$Utc, expected $Expected"
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "2", "--time", $OnA)
Check "BakaShrotGetMessages --time: id, time, data" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t$Expected`t{`"n`":`"stamped`"}") $R.Out
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "2", $OnA)
Check "BakaShrotGetMessages without --time: as before" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t{`"n`":`"stamped`"}") $R.Out
Expect "BakaShrotGetLatestMessage shows it" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnA)) ("#3 \(ids 1:2\), pushed " + [regex]::Escape($Expected))
$Sql = "SELECT message_id, pushed_at FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id"
$OnAStamps = (Query $Sql $OnA).Out
$R = Wait-Query $Sql $OnB '"3","\d+"'
Check "replicated with the same pushed_at, every one" ($R.Out -eq $OnAStamps) "A $OnAStamps | B $($R.Out)"
Expect "BakaShrotGetLatestMessage on B: the same time" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnB)) ("#3 \(ids 300:30\), pushed " + [regex]::Escape($Expected))
"--- Retention on A (short = 3s), not on B (short = forever)"
foreach ($i in 1..3) { Expect "push short #$i" (Push "{`"short`":$i}" $OnA "short") "message #$i" }
$R = Wait-Query (Count "short") $OnB '\[\["3"\]\]' 10
Check "B got the 3 short ones" ($R.Out -match '\[\["3"\]\]') $R.Out
$R = Wait-Query (Count "short") $OnA '\[\["0"\]\]' 10
Check "A deleted them past 3 s" ($R.Out -match '\[\["0"\]\]') $R.Out
Expect "A kept logs (no max age)" (Query (Count "logs") $OnA) '\[\["3"\]\]'
Expect "B kept them (its own rules)" (Query (Count "short") $OnB) '\[\["3"\]\]'
Expect "A: no message left in short" (Tool "BakaShrotGetLatestMessage.exe" @("short", "kitchen", $OnA)) "No message" 1
Expect "A's ids go on after deleting: #4" (Push '{"short":4}' $OnA "short") "message #4"
$R = Wait-Query (Count "short") $OnB '\[\["4"\]\]' 10
Check "B got #4" ($R.Out -match '\[\["4"\]\]') $R.Out
Start-Sleep -Seconds 3
Expect "B didn't send A back what A deleted" (Query (Count "short" "AND message_id <= 3") $OnA) '\[\["0"\]\]'
"--- Retention on B by pattern (ke* = 4s), not on A"
foreach ($i in 1..2) { Expect "push keep #$i" (Push "{`"keep`":$i}" $OnA "keep") "message #$i" }
$R = Wait-Query (Count "keep") $OnB '\[\["2"\]\]' 10
Check "B got the 2 keep ones" ($R.Out -match '\[\["2"\]\]') $R.Out
$R = Wait-Query (Count "keep") $OnB '\[\["0"\]\]' 10
Check "B deleted them past 4 s" ($R.Out -match '\[\["0"\]\]') $R.Out
Expect "A kept them" (Query (Count "keep") $OnA) '\[\["2"\]\]'
Expect "push keep #3" (Push '{"keep":3}' $OnA "keep") "message #3"
$R = Wait-Query (Count "keep") $OnB '\[\["1"\]\]' 10
Check "B only got #3, not #1 and #2 again" ($R.Out -match '\[\["1"\]\]') $R.Out
Expect "B: it's #3" (Tool "BakaShrotGetLatestMessage.exe" @("keep", "kitchen", $OnB)) "keep:kitchen#3"
Expect "B's * = 1h keeps logs" (Query (Count "logs") $OnB) '\[\["3"\]\]'
"--- Replicated already past the max age (B: late = 3s)"
$Head = "SELECT h.max_message_id FROM node_heads h JOIN topics t ON t.topic_id = h.topic_id WHERE t.name = 'late'"
$R = Wait-Query $Head $OnB '\[\["2"\]\]' 10
Check "B counts late #1-#2 as received (its head is 2)" ($R.Out -match '\[\["2"\]\]') $R.Out
Expect "but didn't store them" (Query (Count "late") $OnB) '\[\["0"\]\]'
Expect "A has them" (Query (Count "late") $OnA) '\[\["2"\]\]'
Expect "push late #3, fresh" (Push '{"late":3}' $OnA "late") "message #3"
$R = Wait-Query $Head $OnB '\[\["3"\]\]' 10
Check "B got #3" ($R.Out -match '\[\["3"\]\]') $R.Out
# Stored, then deleted 3 s later by the pass, alone: #1-#2 never were.
$D = (Get-Date).AddSeconds(10)
while ((Get-Date) -lt $D -and -not ((Get-Content (Join-Path $Dir "b.log") -Raw) -match "deleted 1 messages of topic 'late'")) { Start-Sleep -Milliseconds 250 }
Check "B stored #3, and deleted it alone past 3 s" ((Get-Content (Join-Path $Dir "b.log") -Raw) -match "deleted 1 messages of topic 'late'") "checked"
Start-Sleep -Seconds 2
}
finally {
Stop-Srv $SA; if ($SB) { Stop-Srv $SB }
}
"--- Logs"
$LogA = Get-Content (Join-Path $Dir "a.log") -Raw
$LogB = Get-Content (Join-Path $Dir "b.log") -Raw
# How many messages of Topic a log says were deleted. Pushed a few ms apart,
# they can fall on both sides of a retention check (every 1 s), and be
# deleted over two of them.
function Count-Deleted($Log, $Topic) {
$N = 0
foreach ($M in [regex]::Matches($Log, "Retention: deleted (\d+) messages of topic '$Topic' pushed before \d{4}-")) { $N += [int]$M.Groups[1].Value }
$N
}
Check "A logged its rule" ($LogA -match "Retention: short = 3s") "checked"
$N = Count-Deleted $LogA "short"
Check "A logged what it deleted: short #1-#3, maybe #4 since" ($N -ge 3) "$N deleted"
Check "B logged its rules" ($LogB -match "Retention: ke\* = 4s" -and $LogB -match "Retention: \* = 1h") "checked"
$N = Count-Deleted $LogB "keep"
Check "B deleted keep: #1-#2, maybe #3 since" ($N -ge 2) "$N deleted"
Check "B never sent A short messages (A is ahead, deleted or not)" (-not ($LogB -match "Sent \d+ messages of short")) "checked"
Check "A sent B late once each: #1-#2, then #3 alone" (([regex]::Matches($LogA, "Sent 2 messages of late:kitchen")).Count -eq 1 -and ([regex]::Matches($LogA, "Sent 1 messages of late:kitchen")).Count -eq 1) "checked"
Check "B never stored late #1-#2" (-not ($LogB -match "deleted [23] messages of topic 'late'")) "checked"
Check "A sent B keep twice: #1-#2, then #3 alone" ($LogA -match "Sent 2 messages of keep:kitchen" -and $LogA -match "Sent 1 messages of keep:kitchen" -and -not ($LogA -match "Sent 3 messages of keep")) "checked"
# A tries to link to B in the 5 s before B starts: those are expected.
$LinkTries = @([regex]::Matches($LogA, "Failed to link to 'b'")).Count
Check "A only failed to link to B before B started" ($LinkTries -le 8) "$LinkTries tries"
$LogAOther = ($LogA -split "`r?`n" | Where-Object { $_ -notmatch "Failed to link to 'b'|Retrying 'b'" }) -join "`n"
foreach ($P in @("Failed", "invalid", "unexpected", "doesn't decrypt")) {
Check "no '$P' in A's or B's log" (-not ($LogAOther -match [regex]::Escape($P)) -and -not ($LogB -match [regex]::Escape($P))) "checked"
}
"--- An age without a unit"
(Get-Content (Join-Path $Dir "a.ini") -Raw) -replace "short = 3s", "short = 30" | Set-Content (Join-Path $Dir "bad.ini") -Encoding Ascii
$SBad = Start-Srv "bad"
$Exited = $SBad.P.WaitForExit(10000)
if (-not $Exited) { Stop-Srv $SBad }
$LogBad = Get-Content (Join-Path $Dir "bad.log") -Raw
Check "refused at start" ($Exited -and $SBad.P.ExitCode -ne 0 -and $LogBad -match "short = '30' isn't an age") $LogBad.Trim()
""
if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" }
+102
View File
@@ -0,0 +1,102 @@
# X.509 certificates (Commons/Cryptography/Der.pbi, X509.pbi): Build\X509Test.exe's
# own checks, then both ways with OpenSSL, if it's on the PATH (Git for Windows
# has one): OpenSSL's Ed25519 CA, leaf (DER, with BakaShrot's custom extensions)
# and an RSA certificate are read and checked by X509Test.exe; its CA, leaves,
# chain, private key and a leaf it issued with OpenSSL's CA are checked by OpenSSL.
# Needs Build\X509Test.exe (compile Tests\X509Test.pb into it). No server, no port.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\X509-Test.ps1
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"))
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_x509test"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Fails = 0
# BakaShrot's extensions arc (#BakaShrot_Oid_Extensions), the test's numbers.
$Arc = "2.25.232025699926348910519219903487382490981.1"
# X509Test.pb's Now, its certificates are valid then.
$TestNow = 1800000000
function Check([string]$What, [bool]$Ok, [string]$Detail) {
if (-not $Ok) { $script:Fails++ }
if ($Detail.Length -gt 300) { $Detail = $Detail.Substring(0, 300) + "... (" + $Detail.Length + " chars)" }
"{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail
}
$OpenSsl = (Get-Command openssl -ErrorAction SilentlyContinue).Source
if (-not $OpenSsl -and $env:ProgramFiles) {
# Git for Windows' own, when its folders aren't on the PATH.
$OpenSsl = @("ucrt64", "mingw64", "usr") | ForEach-Object { Join-Path $env:ProgramFiles "Git\$_\bin\openssl.exe" } | Where-Object { Test-Path $_ } | Select-Object -First 1
}
# Runs OpenSSL in the test's folder, its output joined (Out).
function Ssl([string[]]$A) {
$ErrorActionPreference = "Continue"
Push-Location $Dir
try { $O = @(& $OpenSsl @A 2>&1 | ForEach-Object { "$_" }) } finally { Pop-Location }
@{ Code = $LASTEXITCODE; Out = ($O -join " | ") }
}
if ($OpenSsl) {
"OpenSSL: $OpenSsl ($((Ssl @("version")).Out))"
$R = Ssl @("genpkey", "-algorithm", "ed25519", "-out", "openssl-ca-key.pem")
Check "OpenSSL: CA key" ($R.Code -eq 0) $R.Out
$R = Ssl @("req", "-x509", "-new", "-key", "openssl-ca-key.pem", "-subj", "/CN=OpenSSL Test CA/O=BakaShrot", "-days", "3650",
"-addext", "basicConstraints=critical,CA:TRUE", "-addext", "keyUsage=critical,keyCertSign,cRLSign", "-out", "openssl-ca.pem")
Check "OpenSSL: CA" ($R.Code -eq 0) $R.Out
$R = Ssl @("genpkey", "-algorithm", "ed25519", "-out", "openssl-leaf-key.pem")
$R = Ssl @("req", "-new", "-key", "openssl-leaf-key.pem", "-subj", "/CN=kitchen", "-out", "openssl-leaf.csr")
Check "OpenSSL: leaf request" ($R.Code -eq 0) $R.Out
Set-Content (Join-Path $Dir "leaf.ext") -Encoding Ascii -Value @"
basicConstraints = critical,CA:FALSE
keyUsage = critical,digitalSignature
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid
$Arc.9000 = ASN1:UTF8String:from-openssl
$Arc.9001 = ASN1:INTEGER:42
"@
$R = Ssl @("x509", "-req", "-in", "openssl-leaf.csr", "-CA", "openssl-ca.pem", "-CAkey", "openssl-ca-key.pem", "-days", "365",
"-extfile", "leaf.ext", "-outform", "DER", "-out", "openssl-leaf.der")
Check "OpenSSL: leaf, with BakaShrot's extensions, as DER" ($R.Code -eq 0) $R.Out
$R = Ssl @("req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", "openssl-rsa-key.pem", "-subj", "/CN=RSA", "-days", "1", "-out", "openssl-rsa.pem")
Check "OpenSSL: an RSA certificate" ($R.Code -eq 0) $R.Out
} else {
"SKIP OpenSSL isn't on the PATH: only X509Test.exe's own checks"
}
# X509Test.exe, from Build\ (the antivirus blocks exes elsewhere).
Push-Location $Build
try { $Out = @(& (Join-Path $Build "X509Test.exe") "$Dir\" 2>&1 | ForEach-Object { "$_" }); $Code = $LASTEXITCODE } finally { Pop-Location }
$Out
$Passed = @($Out | Where-Object { $_ -match "^PASS " }).Count
Check "X509Test.exe" ($Code -eq 0) "exit $Code, $Passed checks passed"
if ($OpenSsl) {
$R = Ssl @("verify", "-attime", "$TestNow", "-CAfile", "bakashrot-ca.pem", "bakashrot-leaf.pem")
Check "OpenSSL verifies BakaShrot's leaf with its CA" (($R.Code -eq 0) -and ($R.Out -match "bakashrot-leaf.pem: OK")) $R.Out
$R = Ssl @("verify", "-attime", "$TestNow", "-CAfile", "bakashrot-ca.pem", "-untrusted", "bakashrot-intermediate.pem", "bakashrot-deep.pem")
Check "OpenSSL verifies BakaShrot's chain (leaf, intermediate, CA)" (($R.Code -eq 0) -and ($R.Out -match "bakashrot-deep.pem: OK")) $R.Out
$R = Ssl @("verify", "-attime", "$TestNow", "-CAfile", "bakashrot-ca.pem", "bakashrot-deep.pem")
Check "OpenSSL refuses the chain without its intermediate" ($R.Code -ne 0) $R.Out
$R = Ssl @("verify", "-attime", "$($TestNow + 2 * 365 * 86400)", "-CAfile", "bakashrot-ca.pem", "bakashrot-leaf.pem")
Check "OpenSSL refuses BakaShrot's leaf once expired" (($R.Code -ne 0) -and ($R.Out -match "expired")) $R.Out
$R = Ssl @("verify", "-CAfile", "openssl-ca.pem", "bakashrot-by-openssl-ca.pem")
Check "OpenSSL verifies a leaf BakaShrot issued with OpenSSL's CA" (($R.Code -eq 0) -and ($R.Out -match ": OK")) $R.Out
$R = Ssl @("x509", "-in", "bakashrot-ca.pem", "-noout", "-text")
Check "OpenSSL reads BakaShrot's CA: Ed25519, CA, path length, key usage" (($R.Out -match "ED25519") -and ($R.Out -match "CA:TRUE, pathlen:1") -and ($R.Out -match "Certificate Sign, CRL Sign") -and ($R.Out -match "Subject: CN=BakaShrot Test CA, O=BakaShrot, C=LU")) $R.Out
$R = Ssl @("x509", "-in", "bakashrot-leaf.pem", "-noout", "-text")
Check "OpenSSL reads BakaShrot's leaf: its custom extensions, key ids" (($R.Out -match [regex]::Escape("$Arc.9000")) -and ($R.Out -match [regex]::Escape("$Arc.9002")) -and ($R.Out -match "Subject Key Identifier") -and ($R.Out -match "Authority Key Identifier") -and ($R.Out -match "Serial Number: 4328719365")) $R.Out
$R = Ssl @("x509", "-in", "bakashrot-leaf.pem", "-noout", "-fingerprint", "-sha256")
$Ours = (Get-Content (Join-Path $Dir "bakashrot-leaf.sha256") -Raw).Trim()
$Theirs = (($R.Out -replace "^.*=", "") -replace ":", "").ToLower()
Check "Fingerprints match OpenSSL's" ($Ours -eq $Theirs) "$Ours / $Theirs"
$Key = Ssl @("pkey", "-in", "bakashrot-leaf-key.pem", "-pubout")
$Cert = Ssl @("x509", "-in", "bakashrot-leaf.pem", "-noout", "-pubkey")
Check "OpenSSL reads BakaShrot's private key, the leaf's" (($Key.Code -eq 0) -and ($Key.Out -eq $Cert.Out) -and ($Key.Out -match "BEGIN PUBLIC KEY")) "$($Key.Out) / $($Cert.Out)"
}
""
if ($Fails) { "$Fails check(s) failed"; exit 1 }
"All checks passed"
exit 0
+745
View File
@@ -0,0 +1,745 @@
;{- Code Header
; ==- Basic Info -================================
; Name: X509Test.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64)
; * PureBasic 6.40 C Backend (Windows x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; Tests of Commons/Cryptography/Der.pbi and X509.pbi, no sockets:
; - DER: integers, lengths, OIDs (2.25 UUID arcs too), times, booleans,
; strings, and what isn't DER refused.
; - Certificates: a CA, an intermediate, leaves with custom extensions,
; issued, read back, checked; every way a check must fail; every
; truncation and every flipped byte of a certificate refused; PEM and
; private keys.
; With a folder argument (Tests/X509-Test.ps1 gives one): also checks the
; certificates OpenSSL made there (openssl-*.pem), and writes its own for
; OpenSSL to check (bakashrot-*.pem).
; Compile as a console program into Build\ (libsodium.dll is there), run it
; from there. Exits with 0 if every check passed, 1 otherwise.
; ============================================================================
EnableExplicit
XIncludeFile "../Commons/Cryptography/X509.pbi"
Global Fails.i = 0
Procedure Check(What.s, Ok.i, Detail.s = "")
If Ok
PrintN("PASS " + What)
Else
PrintN("FAIL " + What)
Fails + 1
EndIf
If Detail <> ""
PrintN(" -> " + Detail)
EndIf
EndProcedure
; Expects a #BakaShrot_X509_* code.
Procedure CheckCode(What.s, Code.i, Expected.i)
Check(What, Bool(Code = Expected), "got " + BakaShrot_X509_ErrorName(Code) + ", expected " + BakaShrot_X509_ErrorName(Expected))
EndProcedure
; Hex ("30 03 02 01 05", spaces ignored) as a new buffer, its size in *Size\i.
Procedure.i FromHex(Hex.s, *Size.Integer)
Protected *Buffer, Size.i
Hex = RemoveString(Hex, " ")
*Buffer = AllocateMemory(Len(Hex) / 2 + 1)
Size = BakaShrot_X509_FromHex(Hex, *Buffer, MemorySize(*Buffer))
*Size\i = Size
ProcedureReturn *Buffer
EndProcedure
; What a writer wrote, in hex.
Procedure.s Written(*Writer.BakaShrot_DerWriter)
Protected *Der, Size.Integer, Hex.s
*Der = BakaShrot_Der_Finish(*Writer, @Size)
If Not *Der
ProcedureReturn "(failed)"
EndIf
Hex = BakaShrot_X509_Hex(*Der, Size\i)
FreeMemory(*Der)
ProcedureReturn Hex
EndProcedure
; Reads the single element in Hex into *Element, its buffer into *Buffer\i
; (free it). #False if it isn't one valid element.
Procedure.i ReadOne(Hex.s, *Element.BakaShrot_DerElement, *Buffer.Integer)
Protected Size.Integer, Reader.BakaShrot_DerReader
*Buffer\i = FromHex(Hex, @Size)
BakaShrot_Der_InitReader(@Reader, *Buffer\i, Size\i)
ProcedureReturn Bool(BakaShrot_Der_Read(@Reader, *Element) And BakaShrot_Der_AtEnd(@Reader))
EndProcedure
Procedure.i IsRefused(Hex.s)
Protected Element.BakaShrot_DerElement, *Buffer, Ok.i
Ok = ReadOne(Hex, @Element, @*Buffer)
FreeMemory(*Buffer)
ProcedureReturn Bool(Not Ok)
EndProcedure
Procedure.s IntegerHex(Value.q)
Protected Writer.BakaShrot_DerWriter
BakaShrot_Der_InitWriter(@Writer)
BakaShrot_Der_WriteInteger(@Writer, Value)
ProcedureReturn Written(@Writer)
EndProcedure
; Whether Value goes through an INTEGER and back.
Procedure.i IntegerRoundTrip(Value.q)
Protected Element.BakaShrot_DerElement, *Buffer, Back.q, Ok.i
Ok = Bool(ReadOne(IntegerHex(Value), @Element, @*Buffer) And BakaShrot_Der_GetInteger(@Element, @Back) And Back = Value)
FreeMemory(*Buffer)
ProcedureReturn Ok
EndProcedure
; The OID read back from writing Oid, "(failed)" if either failed.
Procedure.s OidRoundTrip(Oid.s, *Hex.String = 0)
Protected Writer.BakaShrot_DerWriter, Element.BakaShrot_DerElement, *Buffer, Hex.s, Back.s = "(failed)"
BakaShrot_Der_InitWriter(@Writer)
BakaShrot_Der_WriteOid(@Writer, Oid)
Hex = Written(@Writer)
If *Hex
*Hex\s = Hex
EndIf
If Hex <> "(failed)" And ReadOne(Hex, @Element, @*Buffer)
Back = BakaShrot_Der_GetOid(@Element)
EndIf
If *Buffer
FreeMemory(*Buffer)
EndIf
ProcedureReturn Back
EndProcedure
; The OID in the DER Hex, "" if refused.
Procedure.s OidOf(Hex.s)
Protected Element.BakaShrot_DerElement, *Buffer, Oid.s
If ReadOne(Hex, @Element, @*Buffer)
Oid = BakaShrot_Der_GetOid(@Element)
EndIf
FreeMemory(*Buffer)
ProcedureReturn Oid
EndProcedure
; The time written for Seconds, its tag into *Tag\i, and whether it reads
; back the same.
Procedure.i TimeRoundTrip(Seconds.q, *Tag.Integer)
Protected Writer.BakaShrot_DerWriter, Element.BakaShrot_DerElement, *Buffer, Back.q, Ok.i
BakaShrot_Der_InitWriter(@Writer)
BakaShrot_Der_WriteTime(@Writer, Seconds)
Ok = Bool(ReadOne(Written(@Writer), @Element, @*Buffer) And BakaShrot_Der_GetTime(@Element, @Back) And Back = Seconds)
*Tag\i = Element\Tag
FreeMemory(*Buffer)
ProcedureReturn Ok
EndProcedure
; Whether the time element Tag with Text is refused.
Procedure.i TimeRefused(Tag.i, Text.s)
Protected Element.BakaShrot_DerElement, *Buffer, Seconds.q, Ok.i, Encoded.s, i.i
Encoded = RSet(Hex(Tag), 2, "0") + RSet(Hex(Len(Text)), 2, "0")
For i = 1 To Len(Text)
Encoded + RSet(Hex(Asc(Mid(Text, i, 1))), 2, "0")
Next
Ok = Bool(ReadOne(Encoded, @Element, @*Buffer) And BakaShrot_Der_GetTime(@Element, @Seconds))
FreeMemory(*Buffer)
ProcedureReturn Bool(Not Ok)
EndProcedure
; Issues *Template, returns it parsed (0 if either failed, the code in *Error\l).
Procedure.i IssueParsed(*Template.BakaShrot_X509Template, *Issuer, *Key, *Error.Long)
Protected *Der, Size.Integer, *Cert
*Der = BakaShrot_X509_Issue(*Template, *Issuer, *Key, @Size, *Error)
If Not *Der
ProcedureReturn 0
EndIf
*Cert = BakaShrot_X509_Parse(*Der, Size\i, *Error)
FreeMemory(*Der)
ProcedureReturn *Cert
EndProcedure
Procedure WriteText(Path.s, Text.s)
Protected File.i = CreateFile(#PB_Any, Path)
If File
WriteString(File, Text, #PB_Ascii)
CloseFile(File)
Else
Check("Writing " + Path, #False)
EndIf
EndProcedure
Procedure.s ReadText(Path.s)
Protected *Data, Size.Integer, Text.s
*Data = BakaShrot_X509_ReadFile(Path, @Size)
If *Data
Text = PeekS(*Data, Size\i, #PB_UTF8 | #PB_ByteLength)
FreeMemory(*Data)
EndIf
ProcedureReturn Text
EndProcedure
OpenConsole()
If Not InitCryptography()
PrintN("FAIL libsodium didn't start")
End 1
EndIf
Define Folder.s = ProgramParameter(0)
If Folder <> "" And Right(Folder, 1) <> "\" And Right(Folder, 1) <> "/"
Folder + "/"
EndIf
Define Writer.BakaShrot_DerWriter, Element.BakaShrot_DerElement, Reader.BakaShrot_DerReader
Define *Buffer, Size.Integer, Value.q, Flag.i, Text.String, HexOut.String, Tag.Integer, i.i, Ok.i, Item.s
;- DER: integers
Check("Integer 0", Bool(IntegerHex(0) = "020100"), IntegerHex(0))
Check("Integer 127", Bool(IntegerHex(127) = "02017f"), IntegerHex(127))
Check("Integer 128 gets a sign byte", Bool(IntegerHex(128) = "02020080"), IntegerHex(128))
Check("Integer 256", Bool(IntegerHex(256) = "02020100"), IntegerHex(256))
Check("Integer -1", Bool(IntegerHex(-1) = "0201ff"), IntegerHex(-1))
Check("Integer -128", Bool(IntegerHex(-128) = "020180"), IntegerHex(-128))
Check("Integer -129", Bool(IntegerHex(-129) = "0202ff7f"), IntegerHex(-129))
Ok = #True
For i = 0 To 62
Ok = Ok & IntegerRoundTrip(1 << i) & IntegerRoundTrip(-(1 << i)) & IntegerRoundTrip((1 << i) - 1)
Next
Ok = Ok & IntegerRoundTrip($7FFFFFFFFFFFFFFF) & IntegerRoundTrip(-$7FFFFFFFFFFFFFFF - 1)
Check("Integers round trip, 0 to 2^63", Ok)
ReadOne("0202007f", @Element, @*Buffer)
Check("Integer with a useless 00 refused", Bool(Not BakaShrot_Der_GetInteger(@Element, @Value)))
FreeMemory(*Buffer)
ReadOne("0202ff80", @Element, @*Buffer)
Check("Integer with a useless ff refused", Bool(Not BakaShrot_Der_GetInteger(@Element, @Value)))
FreeMemory(*Buffer)
ReadOne("0200", @Element, @*Buffer)
Check("Empty integer refused", Bool(Not BakaShrot_Der_GetInteger(@Element, @Value)))
FreeMemory(*Buffer)
ReadOne("0209010000000000000000", @Element, @*Buffer)
Check("9-byte integer refused as a small one", Bool(Not BakaShrot_Der_GetInteger(@Element, @Value)))
Check("... but minimal as a big one (a serial)", BakaShrot_Der_IsMinimalInteger(@Element))
FreeMemory(*Buffer)
;- DER: lengths
Check("Long length for under 128 refused", IsRefused("04810100"))
Check("Indefinite length refused", IsRefused("04800000"))
Check("Length with a leading zero refused", IsRefused("0482000100"))
Check("Length past the end refused", IsRefused("04050102"))
Check("Over 4 length bytes refused", IsRefused("0485000000000100"))
Check("High tag number refused", IsRefused("1f0100"))
Check("Nothing refused", IsRefused(""))
Check("A lone tag refused", IsRefused("04"))
Check("Trailing bytes refused", IsRefused("04010000"))
BakaShrot_Der_InitWriter(@Writer)
*Buffer = AllocateMemory(70000)
BakaShrot_Der_Begin(@Writer, #BakaShrot_Der_Sequence)
BakaShrot_Der_WriteOctetString(@Writer, *Buffer, 200)
BakaShrot_Der_Begin(@Writer, #BakaShrot_Der_Sequence)
BakaShrot_Der_WriteOctetString(@Writer, *Buffer, 70000)
BakaShrot_Der_End(@Writer)
BakaShrot_Der_End(@Writer)
FreeMemory(*Buffer)
*Buffer = BakaShrot_Der_Finish(@Writer, @Size)
Ok = #False
If *Buffer
BakaShrot_Der_InitReader(@Reader, *Buffer, Size\i)
If BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_Sequence, @Element) And BakaShrot_Der_AtEnd(@Reader)
BakaShrot_Der_ReaderOf(@Reader, @Element)
Ok = Bool(BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_OctetString, @Element) And Element\ContentSize = 200 And Element\Size = 203)
Ok = Bool(Ok And BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_Sequence, @Element) And Element\ContentSize = 70005 And Element\Size = 70010 And BakaShrot_Der_AtEnd(@Reader))
EndIf
Check("Nested elements of 200 and 70000 bytes: 81 and 83 lengths", Bool(Ok And PeekA(*Buffer + 1) = $83), BakaShrot_X509_Hex(*Buffer, 12))
FreeMemory(*Buffer)
Else
Check("Nested elements of 200 and 70000 bytes", #False, "the writer failed")
EndIf
BakaShrot_Der_InitWriter(@Writer)
BakaShrot_Der_Begin(@Writer, #BakaShrot_Der_Sequence)
Check("A writer with an element left open gives nothing", Bool(Written(@Writer) = "(failed)"))
BakaShrot_Der_InitWriter(@Writer)
BakaShrot_Der_End(@Writer)
Check("An End without a Begin fails the writer", Bool(Written(@Writer) = "(failed)"))
;- DER: OIDs
OidRoundTrip(#BakaShrot_Oid_Ed25519, @HexOut)
Check("OID 1.3.101.112 is 06032b6570", Bool(HexOut\s = "06032b6570"), HexOut\s)
OidRoundTrip("2.999.3", @HexOut)
Check("OID 2.999.3 is 0603883703", Bool(HexOut\s = "0603883703"), HexOut\s)
OidRoundTrip("1.2.840.113549.1.9.1", @HexOut)
Check("OID 1.2.840.113549.1.9.1", Bool(HexOut\s = "06092a864886f70d010901"), HexOut\s)
Ok = #True
Restore Oids
Repeat
Read.s Item
If Item <> ""
If OidRoundTrip(Item) <> Item
Ok = #False
PrintN(" -> " + Item + " came back as " + OidRoundTrip(Item))
EndIf
EndIf
Until Item = ""
Check("OIDs round trip (0.x, 1.x, 2.x, UUID arcs of 128 bits)", Ok)
Check("BakaShrot's arc round trips", Bool(OidRoundTrip(#BakaShrot_Oid_Extensions + ".9000") = #BakaShrot_Oid_Extensions + ".9000"))
OidRoundTrip(#BakaShrot_Oid_Arc, @HexOut)
Check("BakaShrot's arc encoded as Python does it", Bool(HexOut\s = "06146982dd8ec38edbae929ee5a2c2dda290b6a69e65"), HexOut\s)
Ok = #True
Restore BadOids
Repeat
Read.s Item
If Item <> "end"
If BakaShrot_Der_IsValidOid(Item)
Ok = #False
PrintN(" -> '" + Item + "' taken")
EndIf
EndIf
Until Item = "end"
Check("Invalid OID texts refused (empty, one arc, 3.x, 1.40, leading zeros, letters, 141-bit arc)", Ok)
Check("OID with a padded arc refused", Bool(OidOf("06032b8001") = ""))
Check("OID ending mid-arc refused", Bool(OidOf("06022b81") = ""))
Check("Empty OID refused", Bool(OidOf("0600") = ""))
;- DER: times, booleans, strings, bits
Check("1970-01-01 as a UTCTime", Bool(TimeRoundTrip(0, @Tag) And Tag\i = #BakaShrot_Der_UtcTime))
Check("1950-01-01 as a UTCTime", Bool(TimeRoundTrip(-631152000, @Tag) And Tag\i = #BakaShrot_Der_UtcTime))
Check("1949-12-31 23:59:59 as a GeneralizedTime", Bool(TimeRoundTrip(-631152001, @Tag) And Tag\i = #BakaShrot_Der_GeneralizedTime))
Check("2049-12-31 23:59:59 as a UTCTime", Bool(TimeRoundTrip(2524607999, @Tag) And Tag\i = #BakaShrot_Der_UtcTime))
Check("2050-01-01 as a GeneralizedTime", Bool(TimeRoundTrip(2524608000, @Tag) And Tag\i = #BakaShrot_Der_GeneralizedTime))
Check("9999-12-31 23:59:59 (no expiry, RFC 5280)", Bool(TimeRoundTrip(253402300799, @Tag) And Tag\i = #BakaShrot_Der_GeneralizedTime))
Check("2024-02-29 12:34:56 (a leap day)", Bool(TimeRoundTrip(1709210096, @Tag)))
Ok = #True
For i = 0 To 400
Ok = Ok & TimeRoundTrip(i * 31622399 + 1234, @Tag)
Next
Check("Times round trip, 1970 to 2371", Ok)
Check("Month 13 refused", TimeRefused(#BakaShrot_Der_UtcTime, "491301000000Z"))
Check("February 30th refused", TimeRefused(#BakaShrot_Der_UtcTime, "500230000000Z"))
Check("February 29th 2023 refused", TimeRefused(#BakaShrot_Der_UtcTime, "230229000000Z"))
Check("Second 60 refused", TimeRefused(#BakaShrot_Der_UtcTime, "240101000060Z"))
Check("No Z refused", TimeRefused(#BakaShrot_Der_GeneralizedTime, "202401010000001"))
Check("No seconds refused", TimeRefused(#BakaShrot_Der_UtcTime, "2401010000Z"))
Check("Fractions refused", TimeRefused(#BakaShrot_Der_GeneralizedTime, "20240101000000.5Z"))
Check("A time zone refused", TimeRefused(#BakaShrot_Der_UtcTime, "240101000000+0100"))
Check("Non-digits refused", TimeRefused(#BakaShrot_Der_UtcTime, "24O101000000Z"))
ReadOne("0101ff", @Element, @*Buffer)
Check("Boolean ff is true", Bool(BakaShrot_Der_GetBoolean(@Element, @Flag) And Flag = #True))
FreeMemory(*Buffer)
ReadOne("010101", @Element, @*Buffer)
Check("Boolean 01 refused", Bool(Not BakaShrot_Der_GetBoolean(@Element, @Flag)))
FreeMemory(*Buffer)
ReadOne("0c03e282ac", @Element, @*Buffer)
Check("UTF8String", Bool(BakaShrot_Der_GetText(@Element, @Text) And Text\s = Chr($20AC)))
FreeMemory(*Buffer)
ReadOne("1e0400e920ac", @Element, @*Buffer)
Check("BMPString", Bool(BakaShrot_Der_GetText(@Element, @Text) And Text\s = Chr($E9) + Chr($20AC)))
FreeMemory(*Buffer)
ReadOne("0c03610062", @Element, @*Buffer)
Check("A NUL in a string refused", Bool(Not BakaShrot_Der_GetText(@Element, @Text)))
FreeMemory(*Buffer)
ReadOne("1302e961", @Element, @*Buffer)
Check("PrintableString that isn't ASCII refused", Bool(Not BakaShrot_Der_GetText(@Element, @Text)))
FreeMemory(*Buffer)
BakaShrot_Der_InitWriter(@Writer)
BakaShrot_Der_WriteText(@Writer, #BakaShrot_Der_PrintableString, "a_b")
Check("Writing '_' in a PrintableString refused", Bool(Written(@Writer) = "(failed)"))
BakaShrot_Der_InitWriter(@Writer)
BakaShrot_Der_WriteBitFlags(@Writer, #BakaShrot_X509_KeyUsage_KeyCertSign | #BakaShrot_X509_KeyUsage_CrlSign)
Check("KeyUsage keyCertSign + cRLSign is 03020106", Bool(Written(@Writer) = "03020106"))
BakaShrot_Der_InitWriter(@Writer)
BakaShrot_Der_WriteBitFlags(@Writer, #BakaShrot_X509_KeyUsage_DigitalSignature | #BakaShrot_X509_KeyUsage_DecipherOnly)
Check("KeyUsage digitalSignature + decipherOnly is 0303078080", Bool(Written(@Writer) = "0303078080"))
ReadOne("0303078080", @Element, @*Buffer)
Check("... and reads back", Bool(BakaShrot_Der_GetBitFlags(@Element, @Flag) And Flag = (#BakaShrot_X509_KeyUsage_DigitalSignature | #BakaShrot_X509_KeyUsage_DecipherOnly)))
FreeMemory(*Buffer)
ReadOne("03020107", @Element, @*Buffer)
Check("Unused bits that aren't zero refused", Bool(Not BakaShrot_Der_GetBitFlags(@Element, @Flag)))
FreeMemory(*Buffer)
;- Certificates
Define Now.q = 1800000000
Define Year.q = 365 * 86400
Dim CaPub.a(31) : Dim CaKey.a(63)
Dim InterPub.a(31) : Dim InterKey.a(63)
Dim LeafPub.a(31) : Dim LeafKey.a(63)
Dim OtherPub.a(31) : Dim OtherKey.a(63)
GenerateKeyPair(@CaPub(0), @CaKey(0))
GenerateKeyPair(@InterPub(0), @InterKey(0))
GenerateKeyPair(@LeafPub(0), @LeafKey(0))
GenerateKeyPair(@OtherPub(0), @OtherKey(0))
Define Template.BakaShrot_X509Template, Error.Long, *Der, DerSize.Integer
Define *Ca.BakaShrot_X509Certificate, *Inter.BakaShrot_X509Certificate, *Leaf.BakaShrot_X509Certificate
Define *Other.BakaShrot_X509Certificate, *Cert.BakaShrot_X509Certificate, *Copy.BakaShrot_X509Certificate
Define NewList Chain.i()
Define TextExtension.s = #BakaShrot_Oid_Extensions + ".9000"
Define IntegerExtension.s = #BakaShrot_Oid_Extensions + ".9001"
Define RawExtension.s = #BakaShrot_Oid_Extensions + ".9002"
Define CriticalExtension.s = #BakaShrot_Oid_Extensions + ".9003"
; The CA, self-signed.
BakaShrot_X509_InitTemplate(@Template)
BakaShrot_X509_NameAdd(@Template\Subject, "CN", "BakaShrot Test CA")
BakaShrot_X509_NameAdd(@Template\Subject, "O", "BakaShrot")
BakaShrot_X509_NameAdd(@Template\Subject, "C", "LU")
Template\NotBefore = Now - 3600
Template\NotAfter = Now + 10 * Year
Template\IsCa = #True
Template\PathLength = 1
Template\KeyUsage = #BakaShrot_X509_KeyUsage_KeyCertSign | #BakaShrot_X509_KeyUsage_CrlSign
CopyMemory(@CaPub(0), @Template\PublicKey[0], 32)
Check("A self-signed certificate needs the subject's own key", Bool(BakaShrot_X509_Issue(@Template, 0, @OtherKey(0), @DerSize, @Error) = 0 And Error\l = #BakaShrot_X509_Error_KeyMismatch))
*Ca = IssueParsed(@Template, 0, @CaKey(0), @Error)
BakaShrot_X509_ClearTemplate(@Template)
Check("CA issued and read back", Bool(*Ca <> 0), BakaShrot_X509_ErrorName(Error\l))
If Not *Ca
PrintN("Can't go on without the CA")
End 1
EndIf
Check("CA: version 3, Ed25519", Bool(*Ca\Version = 3 And *Ca\SignatureAlgorithm = #BakaShrot_Oid_Ed25519 And *Ca\KeyAlgorithm = #BakaShrot_Oid_Ed25519 And *Ca\HasEd25519Key And *Ca\HasEd25519Signature))
Check("CA: subject", Bool(BakaShrot_X509_NameToString(@*Ca\Subject) = "CN=BakaShrot Test CA, O=BakaShrot, C=LU"), BakaShrot_X509_NameToString(@*Ca\Subject))
Check("CA: CN, and C as a PrintableString", Bool(BakaShrot_X509_NameGet(@*Ca\Subject, "cn") = "BakaShrot Test CA" And *Ca\Subject\Attributes(2)\StringTag = #BakaShrot_Der_PrintableString))
Check("CA: issuer is its subject", Bool(*Ca\IssuerSize = *Ca\SubjectSize And CompareMemory(*Ca\Der + *Ca\IssuerOffset, *Ca\Der + *Ca\SubjectOffset, *Ca\IssuerSize)))
Check("CA: validity", Bool(*Ca\NotBefore = Now - 3600 And *Ca\NotAfter = Now + 10 * Year))
Check("CA: its key", CompareMemory(@*Ca\PublicKey[0], @CaPub(0), 32))
Check("CA: CA, path length 1, key usage", Bool(*Ca\HasBasicConstraints And *Ca\IsCa And *Ca\PathLength = 1 And *Ca\HasKeyUsage And *Ca\KeyUsage = Template\KeyUsage))
Check("CA: key ids, its own as the authority's", Bool(Len(*Ca\SubjectKeyId) = 40 And *Ca\AuthorityKeyId = *Ca\SubjectKeyId))
Check("CA: a random 16-byte positive serial", Bool(Len(*Ca\Serial) = 32 And Val("$" + Left(*Ca\Serial, 2)) >= $40 And Val("$" + Left(*Ca\Serial, 2)) < $80), *Ca\Serial)
Check("CA: 4 extensions", Bool(*Ca\ExtensionCount = 4 And BakaShrot_X509_FindExtension(*Ca, #BakaShrot_Oid_BasicConstraints) = 0 And *Ca\Extensions(0)\Critical And *Ca\Extensions(1)\Critical And Not *Ca\Extensions(2)\Critical))
CheckCode("CA: signed by itself", BakaShrot_X509_CheckSignature(*Ca, @CaPub(0)), #BakaShrot_X509_Ok)
CheckCode("CA: not by another key", BakaShrot_X509_CheckSignature(*Ca, @OtherPub(0)), #BakaShrot_X509_Error_BadSignature)
CheckCode("CA: issued by itself", BakaShrot_X509_CheckIssuedBy(*Ca, *Ca, Now), #BakaShrot_X509_Ok)
Check("CA: fingerprint, the same for the same DER", Bool(Len(BakaShrot_X509_Fingerprint(*Ca)) = 64))
; The leaf: a client, with custom extensions.
BakaShrot_X509_InitTemplate(@Template)
BakaShrot_X509_NameAdd(@Template\Subject, "CN", "kitchen")
BakaShrot_X509_NameAdd(@Template\Subject, "OU", "clients")
Template\Serial = "0102030405"
Template\NotBefore = Now - 60
Template\NotAfter = Now + Year
Template\KeyUsage = #BakaShrot_X509_KeyUsage_DigitalSignature
CopyMemory(@LeafPub(0), @Template\PublicKey[0], 32)
Check("Text extension added", BakaShrot_X509_AddTextExtension(@Template, TextExtension, "kitchen " + Chr($20AC)))
Check("Integer extension added", BakaShrot_X509_AddIntegerExtension(@Template, IntegerExtension, -1234567890123))
BakaShrot_Der_InitWriter(@Writer)
BakaShrot_Der_Begin(@Writer, #BakaShrot_Der_Sequence)
BakaShrot_Der_WriteText(@Writer, #BakaShrot_Der_Utf8String, "logs")
BakaShrot_Der_WriteText(@Writer, #BakaShrot_Der_Utf8String, "sensors")
BakaShrot_Der_End(@Writer)
*Der = BakaShrot_Der_Finish(@Writer, @DerSize)
Check("Any DER extension added", BakaShrot_X509_AddExtension(@Template, RawExtension, *Der, DerSize\i))
Check("The same OID twice refused", Bool(Not BakaShrot_X509_AddExtension(@Template, RawExtension, *Der, DerSize\i)))
Check("A standard extension refused (Issue writes it)", Bool(Not BakaShrot_X509_AddExtension(@Template, #BakaShrot_Oid_KeyUsage, *Der, DerSize\i)))
Check("A value that isn't one DER element refused", Bool(Not BakaShrot_X509_AddExtension(@Template, CriticalExtension, *Der, DerSize\i - 1)))
Check("An invalid OID refused", Bool(Not BakaShrot_X509_AddTextExtension(@Template, "1.2.03", "x")))
FreeMemory(*Der)
Template\PathLength = 0
Check("A leaf with a path length refused", Bool(BakaShrot_X509_Issue(@Template, *Ca, @CaKey(0), @DerSize, @Error) = 0 And Error\l = #BakaShrot_X509_Error_InvalidArgument))
Template\PathLength = -1
Check("Issuing needs the issuer's key", Bool(BakaShrot_X509_Issue(@Template, *Ca, @OtherKey(0), @DerSize, @Error) = 0 And Error\l = #BakaShrot_X509_Error_KeyMismatch))
*Leaf = IssueParsed(@Template, *Ca, @CaKey(0), @Error)
Check("Leaf issued by the CA and read back", Bool(*Leaf <> 0), BakaShrot_X509_ErrorName(Error\l))
If Not *Leaf
PrintN("Can't go on without the leaf")
End 1
EndIf
Check("Leaf: issuer, subject, serial", Bool(BakaShrot_X509_NameToString(@*Leaf\Issuer) = BakaShrot_X509_NameToString(@*Ca\Subject) And BakaShrot_X509_NameGet(@*Leaf\Subject, "CN") = "kitchen" And *Leaf\Serial = "0102030405"), *Leaf\Serial)
Check("Leaf: not a CA, no path length", Bool(*Leaf\HasBasicConstraints And Not *Leaf\IsCa And *Leaf\PathLength = -1 And *Leaf\KeyUsage = #BakaShrot_X509_KeyUsage_DigitalSignature))
Check("Leaf: the CA's key id as its authority's", Bool(*Leaf\AuthorityKeyId = *Ca\SubjectKeyId And *Leaf\SubjectKeyId <> *Ca\SubjectKeyId))
Check("Leaf: text extension", Bool(BakaShrot_X509_GetExtensionText(*Leaf, TextExtension, @Text) And Text\s = "kitchen " + Chr($20AC)), Text\s)
Check("Leaf: integer extension", Bool(BakaShrot_X509_GetExtensionInteger(*Leaf, IntegerExtension, @Value) And Value = -1234567890123))
i = BakaShrot_X509_FindExtension(*Leaf, RawExtension)
Check("Leaf: raw extension, as given", Bool(i >= 0 And *Leaf\Extensions(i)\ValueSize = 17 And Not *Leaf\Extensions(i)\Critical))
Check("Leaf: no such extension", Bool(BakaShrot_X509_FindExtension(*Leaf, CriticalExtension) = -1 And Not BakaShrot_X509_GetExtensionText(*Leaf, CriticalExtension, @Text)))
Check("Leaf: a text extension isn't an integer", Bool(Not BakaShrot_X509_GetExtensionInteger(*Leaf, TextExtension, @Value)))
CheckCode("Leaf: issued by the CA", BakaShrot_X509_CheckIssuedBy(*Leaf, *Ca, Now), #BakaShrot_X509_Ok)
CheckCode("Leaf: valid from its NotBefore", BakaShrot_X509_CheckIssuedBy(*Leaf, *Ca, Now - 60), #BakaShrot_X509_Ok)
CheckCode("Leaf: valid up to its NotAfter", BakaShrot_X509_CheckIssuedBy(*Leaf, *Ca, Now + Year), #BakaShrot_X509_Ok)
CheckCode("Leaf: not yet valid", BakaShrot_X509_CheckIssuedBy(*Leaf, *Ca, Now - 61), #BakaShrot_X509_Error_NotYetValid)
CheckCode("Leaf: expired", BakaShrot_X509_CheckIssuedBy(*Leaf, *Ca, Now + Year + 1), #BakaShrot_X509_Error_Expired)
CheckCode("Leaf: not issued by itself", BakaShrot_X509_CheckIssuedBy(*Leaf, *Leaf, Now), #BakaShrot_X509_Error_IssuerMismatch)
AddElement(Chain()) : Chain() = *Leaf
CheckCode("Leaf: chain up to the CA", BakaShrot_X509_VerifyChain(Chain(), *Ca, Now), #BakaShrot_X509_Ok)
CheckCode("Leaf: chain, the CA expired", BakaShrot_X509_VerifyChain(Chain(), *Ca, Now + 11 * Year), #BakaShrot_X509_Error_Expired)
Check("Leaf can't issue", Bool(BakaShrot_X509_Issue(@Template, *Leaf, @LeafKey(0), @DerSize, @Error) = 0 And Error\l = #BakaShrot_X509_Error_NotCa))
CheckCode("A leaf as a root refused", BakaShrot_X509_VerifyChain(Chain(), *Leaf, Now), #BakaShrot_X509_Error_NotCa)
Check("Describe", Bool(FindString(BakaShrot_X509_Describe(*Leaf), "CN=kitchen, OU=clients") > 0 And FindString(BakaShrot_X509_Describe(*Leaf), TextExtension) > 0))
BakaShrot_X509_ClearTemplate(@Template)
; Another CA with the same name, another key: its key id doesn't match.
BakaShrot_X509_InitTemplate(@Template)
BakaShrot_X509_NameAdd(@Template\Subject, "CN", "BakaShrot Test CA")
BakaShrot_X509_NameAdd(@Template\Subject, "O", "BakaShrot")
BakaShrot_X509_NameAdd(@Template\Subject, "C", "LU")
Template\NotBefore = Now - 3600
Template\NotAfter = Now + Year
Template\IsCa = #True
CopyMemory(@OtherPub(0), @Template\PublicKey[0], 32)
*Other = IssueParsed(@Template, 0, @OtherKey(0), @Error)
CheckCode("Same name, other CA: key ids differ", BakaShrot_X509_CheckIssuedBy(*Leaf, *Other, Now), #BakaShrot_X509_Error_IssuerMismatch)
BakaShrot_X509_Free(*Other)
BakaShrot_X509_ClearTemplate(@Template)
*Other = 0
; A CA that may only sign CRLs.
BakaShrot_X509_InitTemplate(@Template)
BakaShrot_X509_NameAdd(@Template\Subject, "CN", "CRL only")
Template\NotBefore = Now - 3600
Template\NotAfter = Now + Year
Template\IsCa = #True
Template\KeyUsage = #BakaShrot_X509_KeyUsage_CrlSign
CopyMemory(@OtherPub(0), @Template\PublicKey[0], 32)
*Other = IssueParsed(@Template, 0, @OtherKey(0), @Error)
Check("A CA without keyCertSign can't issue", Bool(*Other <> 0 And BakaShrot_X509_CanIssue(*Other) = #False))
BakaShrot_X509_ClearTemplate(@Template)
; A leaf with a critical custom extension.
BakaShrot_X509_InitTemplate(@Template)
BakaShrot_X509_NameAdd(@Template\Subject, "CN", "strict")
Template\NotBefore = Now - 60
Template\NotAfter = Now + Year
CopyMemory(@LeafPub(0), @Template\PublicKey[0], 32)
BakaShrot_X509_AddTextExtension(@Template, CriticalExtension, "must be understood", #True)
*Cert = IssueParsed(@Template, *Ca, @CaKey(0), @Error)
CheckCode("Critical extension nobody handles", BakaShrot_X509_CheckIssuedBy(*Cert, *Ca, Now), #BakaShrot_X509_Error_UnknownCritical)
CheckCode("... handled by the caller", BakaShrot_X509_CheckIssuedBy(*Cert, *Ca, Now, "1.2.3;" + CriticalExtension), #BakaShrot_X509_Ok)
BakaShrot_X509_Free(*Cert)
BakaShrot_X509_ClearTemplate(@Template)
; A name that can't be written.
BakaShrot_X509_InitTemplate(@Template)
BakaShrot_X509_NameAdd(@Template\Subject, "C", "LUX")
Template\NotAfter = Now
CopyMemory(@LeafPub(0), @Template\PublicKey[0], 32)
Check("A 3-letter country refused", Bool(BakaShrot_X509_Issue(@Template, *Ca, @CaKey(0), @DerSize, @Error) = 0))
Check("An unknown name type refused", Bool(Not BakaShrot_X509_NameAdd(@Template\Subject, "XX", "x")))
Template\Subject\Count = 0
Template\NotBefore = Now + 1
Check("NotAfter before NotBefore refused", Bool(BakaShrot_X509_Issue(@Template, *Ca, @CaKey(0), @DerSize, @Error) = 0 And Error\l = #BakaShrot_X509_Error_InvalidArgument))
BakaShrot_X509_ClearTemplate(@Template)
; Chains: CA (path length 1) -> intermediate (path length 0) -> leaf.
BakaShrot_X509_InitTemplate(@Template)
BakaShrot_X509_NameAdd(@Template\Subject, "CN", "Intermediate")
Template\NotBefore = Now - 3600
Template\NotAfter = Now + 5 * Year
Template\IsCa = #True
Template\PathLength = 0
Template\KeyUsage = #BakaShrot_X509_KeyUsage_KeyCertSign
CopyMemory(@InterPub(0), @Template\PublicKey[0], 32)
*Inter = IssueParsed(@Template, *Ca, @CaKey(0), @Error)
BakaShrot_X509_ClearTemplate(@Template)
BakaShrot_X509_InitTemplate(@Template)
BakaShrot_X509_NameAdd(@Template\Subject, "CN", "deep")
Template\NotBefore = Now - 60
Template\NotAfter = Now + Year
CopyMemory(@LeafPub(0), @Template\PublicKey[0], 32)
*Cert = IssueParsed(@Template, *Inter, @InterKey(0), @Error)
BakaShrot_X509_ClearTemplate(@Template)
Check("Intermediate and its leaf issued", Bool(*Inter <> 0 And *Cert <> 0))
ClearList(Chain())
AddElement(Chain()) : Chain() = *Cert
AddElement(Chain()) : Chain() = *Inter
CheckCode("Leaf, intermediate, CA (path length 1)", BakaShrot_X509_VerifyChain(Chain(), *Ca, Now), #BakaShrot_X509_Ok)
If Folder <> ""
WriteText(Folder + "bakashrot-deep.pem", BakaShrot_X509_ToPem(*Cert))
EndIf
ClearList(Chain())
AddElement(Chain()) : Chain() = *Cert
CheckCode("The intermediate missing", BakaShrot_X509_VerifyChain(Chain(), *Ca, Now), #BakaShrot_X509_Error_IssuerMismatch)
; The intermediate (path length 0) under itself: one CA too many.
BakaShrot_X509_InitTemplate(@Template)
BakaShrot_X509_NameAdd(@Template\Subject, "CN", "Sub-intermediate")
Template\NotBefore = Now - 3600
Template\NotAfter = Now + Year
Template\IsCa = #True
CopyMemory(@OtherPub(0), @Template\PublicKey[0], 32)
BakaShrot_X509_Free(*Other)
*Other = IssueParsed(@Template, *Inter, @InterKey(0), @Error)
BakaShrot_X509_ClearTemplate(@Template)
BakaShrot_X509_InitTemplate(@Template)
BakaShrot_X509_NameAdd(@Template\Subject, "CN", "deeper")
Template\NotBefore = Now - 60
Template\NotAfter = Now + Year
CopyMemory(@LeafPub(0), @Template\PublicKey[0], 32)
*Copy = IssueParsed(@Template, *Other, @OtherKey(0), @Error)
BakaShrot_X509_ClearTemplate(@Template)
ClearList(Chain())
AddElement(Chain()) : Chain() = *Copy
AddElement(Chain()) : Chain() = *Other
AddElement(Chain()) : Chain() = *Inter
CheckCode("A CA under a path length 0 one", BakaShrot_X509_VerifyChain(Chain(), *Ca, Now), #BakaShrot_X509_Error_PathTooLong)
BakaShrot_X509_Free(*Copy)
BakaShrot_X509_Free(*Cert)
; Damage: every truncation, every flipped byte, trailing data.
*Buffer = AllocateMemory(*Leaf\DerSize + 1)
Ok = #True
For i = 0 To *Leaf\DerSize - 1
*Cert = BakaShrot_X509_Parse(*Leaf\Der, i, @Error)
If *Cert
Ok = #False
BakaShrot_X509_Free(*Cert)
EndIf
Next
Check("Every truncation of the leaf refused (" + Str(*Leaf\DerSize) + ")", Ok)
Define Taken.i = 0, Parsed.i = 0
For i = 0 To *Leaf\DerSize - 1
CopyMemory(*Leaf\Der, *Buffer, *Leaf\DerSize)
PokeA(*Buffer + i, PeekA(*Buffer + i) ! $01)
*Cert = BakaShrot_X509_Parse(*Buffer, *Leaf\DerSize)
If *Cert
Parsed + 1
If BakaShrot_X509_CheckIssuedBy(*Cert, *Ca, Now, CriticalExtension) = #BakaShrot_X509_Ok
Taken + 1
EndIf
BakaShrot_X509_Free(*Cert)
EndIf
Next
Check("Every flipped bit of the leaf refused, by parsing or checking", Bool(Taken = 0), Str(Parsed) + " of " + Str(*Leaf\DerSize) + " still parsed, " + Str(Taken) + " taken")
CopyMemory(*Leaf\Der, *Buffer, *Leaf\DerSize)
PokeA(*Buffer + *Leaf\DerSize, 0)
Check("Trailing data refused", Bool(BakaShrot_X509_Parse(*Buffer, *Leaf\DerSize + 1, @Error) = 0 And Error\l = #BakaShrot_X509_Error_Malformed))
CopyMemory(*Leaf\Der, *Buffer, *Leaf\DerSize)
PokeA(*Buffer + *Leaf\DerSize - 1, PeekA(*Buffer + *Leaf\DerSize - 1) ! $80)
*Cert = BakaShrot_X509_Parse(*Buffer, *Leaf\DerSize)
Check("A damaged signature: read, but refused", Bool(*Cert <> 0 And BakaShrot_X509_CheckIssuedBy(*Cert, *Ca, Now) = #BakaShrot_X509_Error_BadSignature))
BakaShrot_X509_Free(*Cert)
FreeMemory(*Buffer)
Check("Nothing refused", Bool(BakaShrot_X509_Parse(0, 0, @Error) = 0 And Error\l = #BakaShrot_X509_Error_InvalidArgument))
; PEM
Define Pem.s = BakaShrot_X509_ToPem(*Leaf)
*Cert = BakaShrot_X509_ParsePem(Pem)
Check("PEM round trip", Bool(*Cert <> 0 And *Cert\DerSize = *Leaf\DerSize And CompareMemory(*Cert\Der, *Leaf\Der, *Leaf\DerSize) And Left(Pem, 27) = "-----BEGIN CERTIFICATE-----"))
BakaShrot_X509_Free(*Cert)
*Cert = BakaShrot_X509_ParsePem("Some text" + #CRLF$ + ReplaceString(Pem, #LF$, #CRLF$) + "more text")
Check("PEM with CRLF, text around it", Bool(*Cert <> 0))
BakaShrot_X509_Free(*Cert)
Check("PEM with a bad character refused", Bool(BakaShrot_X509_ParsePem(Left(Pem, 40) + "*" + Mid(Pem, 41)) = 0))
Check("PEM of another label refused", Bool(BakaShrot_X509_ParsePem(ReplaceString(Pem, "CERTIFICATE", "PUBLIC KEY")) = 0))
Check("PEM without its end refused", Bool(BakaShrot_X509_ParsePem(Left(Pem, Len(Pem) - 30)) = 0))
; Private keys
Dim Back.a(63)
Pem = BakaShrot_X509_PrivateKeyToPem(@LeafKey(0))
Check("Private key PEM round trip", Bool(BakaShrot_X509_PrivateKeyFromPem(Pem, @Back(0)) And CompareMemory(@Back(0), @LeafKey(0), 64) And Left(Pem, 27) = "-----BEGIN PRIVATE KEY-----"))
Check("A certificate isn't a private key", Bool(Not BakaShrot_X509_PrivateKeyFromPem(BakaShrot_X509_ToPem(*Leaf), @Back(0))))
;- OpenSSL, both ways
If Folder <> ""
WriteText(Folder + "bakashrot-ca.pem", BakaShrot_X509_ToPem(*Ca))
WriteText(Folder + "bakashrot-intermediate.pem", BakaShrot_X509_ToPem(*Inter))
WriteText(Folder + "bakashrot-leaf.pem", BakaShrot_X509_ToPem(*Leaf))
WriteText(Folder + "bakashrot-leaf-key.pem", BakaShrot_X509_PrivateKeyToPem(@LeafKey(0)))
WriteText(Folder + "bakashrot-leaf.sha256", BakaShrot_X509_Fingerprint(*Leaf))
PrintN("Wrote bakashrot-*.pem")
If FileSize(Folder + "openssl-ca.pem") > 0
Define *OpenSslCa.BakaShrot_X509Certificate = BakaShrot_X509_Load(Folder + "openssl-ca.pem", @Error)
Define *OpenSslLeaf.BakaShrot_X509Certificate = BakaShrot_X509_Load(Folder + "openssl-leaf.der", @Error)
Define *Rsa.BakaShrot_X509Certificate = BakaShrot_X509_Load(Folder + "openssl-rsa.pem", @Error)
Define OpenSslNow.q
Check("OpenSSL's CA read", Bool(*OpenSslCa <> 0))
Check("OpenSSL's leaf read (DER)", Bool(*OpenSslLeaf <> 0))
If *OpenSslCa And *OpenSslLeaf
OpenSslNow = *OpenSslLeaf\NotBefore + 60
Check("OpenSSL's CA: a CA with its key ids", Bool(*OpenSslCa\IsCa And BakaShrot_X509_CanIssue(*OpenSslCa) And *OpenSslCa\SubjectKeyId <> ""))
Check("OpenSSL's leaf: names", Bool(BakaShrot_X509_NameGet(@*OpenSslLeaf\Subject, "CN") = "kitchen" And BakaShrot_X509_NameGet(@*OpenSslLeaf\Issuer, "CN") = "OpenSSL Test CA"), BakaShrot_X509_NameToString(@*OpenSslLeaf\Subject))
Check("OpenSSL's leaf: our text extension", Bool(BakaShrot_X509_GetExtensionText(*OpenSslLeaf, TextExtension, @Text) And Text\s = "from-openssl"), Text\s)
Check("OpenSSL's leaf: our integer extension", Bool(BakaShrot_X509_GetExtensionInteger(*OpenSslLeaf, IntegerExtension, @Value) And Value = 42))
CheckCode("OpenSSL's leaf: issued by OpenSSL's CA", BakaShrot_X509_CheckIssuedBy(*OpenSslLeaf, *OpenSslCa, OpenSslNow), #BakaShrot_X509_Ok)
CheckCode("OpenSSL's leaf: not by ours", BakaShrot_X509_CheckIssuedBy(*OpenSslLeaf, *Ca, OpenSslNow), #BakaShrot_X509_Error_IssuerMismatch)
; Issued here with OpenSSL's CA and key, for OpenSSL to check.
Dim OpenSslKey.a(63)
Dim OpenSslPub.a(31)
Check("OpenSSL's private key read", BakaShrot_X509_PrivateKeyFromPem(ReadText(Folder + "openssl-ca-key.pem"), @OpenSslKey(0)))
GetPublicKeyFromPrivateKey(@OpenSslKey(0), @OpenSslPub(0))
Check("... and it's its CA's", CompareMemory(@OpenSslPub(0), @*OpenSslCa\PublicKey[0], 32))
BakaShrot_X509_InitTemplate(@Template)
BakaShrot_X509_NameAdd(@Template\Subject, "CN", "garage")
Template\NotBefore = BakaShrot_X509_Now() - 3600
Template\NotAfter = BakaShrot_X509_Now() + Year
Template\KeyUsage = #BakaShrot_X509_KeyUsage_DigitalSignature
CopyMemory(@LeafPub(0), @Template\PublicKey[0], 32)
BakaShrot_X509_AddTextExtension(@Template, TextExtension, "from-bakashrot")
*Der = BakaShrot_X509_Issue(@Template, *OpenSslCa, @OpenSslKey(0), @DerSize, @Error)
BakaShrot_X509_ClearTemplate(@Template)
Check("Issued with OpenSSL's CA", Bool(*Der <> 0), BakaShrot_X509_ErrorName(Error\l))
If *Der
WriteText(Folder + "bakashrot-by-openssl-ca.pem", BakaShrot_Pem_Encode(*Der, DerSize\i, "CERTIFICATE"))
FreeMemory(*Der)
EndIf
EndIf
Check("OpenSSL's RSA certificate read", Bool(*Rsa <> 0 And *Rsa\KeyAlgorithm = "1.2.840.113549.1.1.1" And Not *Rsa\HasEd25519Key And BakaShrot_X509_NameGet(@*Rsa\Subject, "CN") = "RSA"))
If *Rsa
CheckCode("... it can't be checked", BakaShrot_X509_CheckSignature(*Rsa, @CaPub(0)), #BakaShrot_X509_Error_Unsupported)
Check("... nor issue", Bool(BakaShrot_X509_Issue(@Template, *Rsa, @CaKey(0), @DerSize, @Error) = 0 And Error\l = #BakaShrot_X509_Error_Unsupported))
EndIf
BakaShrot_X509_Free(*OpenSslCa)
BakaShrot_X509_Free(*OpenSslLeaf)
BakaShrot_X509_Free(*Rsa)
Else
PrintN("SKIP OpenSSL's certificates: none in " + Folder)
EndIf
EndIf
BakaShrot_X509_Free(*Ca)
BakaShrot_X509_Free(*Inter)
BakaShrot_X509_Free(*Leaf)
BakaShrot_X509_Free(*Other)
PrintN("")
If Fails
PrintN(Str(Fails) + " check(s) failed")
End 1
EndIf
PrintN("All checks passed")
End 0
DataSection
Oids:
Data.s "0.0", "0.39", "1.0", "1.39", "2.0", "2.47", "2.48", "2.999", "2.5.29.19", "1.3.6.1.4.1.311.21.7"
Data.s "0.9.2342.19200300.100.1.25", "2.25.232025699926348910519219903487382490981"
Data.s "2.25.340282366920938463463374607431768211455", "1.2.18446744073709551615.18446744073709551616"
Data.s "1.2.1393796574908163946345982392040522594123775"
Data.s ""
BadOids:
Data.s "", "1", "3.1", "1.40", "0.40", "1.2.03", "1..2", "1.2.", ".1.2", "a.b", "1.2.-3", "1.2. 3"
Data.s "1.2.1393796574908163946345982392040522594123776"
Data.s "end"
EndDataSection
+36
View File
@@ -0,0 +1,36 @@
"""Pushes as fast as the server acknowledges, for Tests/Restart-Test.ps1.
Usage: restart_pusher.py <BakaShrot_Client.dll> <client.ini> <stop file> <out file> <tag>
Pushes {"by": tag, "seq": n} to the client's DefaultTopic until the stop
file exists, writing "<message id> <seq>" to the out file once each push is
acknowledged. Ends with "STOPPED", or "ERR <code> <why>" when the server
goes away (the test kills it; code 104, ConnectionLost, during a push, or
100, NotConnected, between two): what was
acknowledged before is what must survive.
"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "Interactors", "Python"))
from bakashrot import BakaShrotError, Client # noqa: E402
dll_path, ini_path, stop_path, out_path, tag = sys.argv[1:6]
client = Client.from_ini(ini_path, dll_path)
with open(out_path, "a", buffering=1) as out:
try:
client.connect()
seq = 0
while not os.path.exists(stop_path):
seq += 1
message_id = client.push({"by": tag, "seq": seq})
out.write(f"{message_id} {seq}\n")
out.write("STOPPED\n")
except BakaShrotError as error:
out.write(f"ERR {int(error.code)} {type(error).__name__}: {error}\n")
finally:
try:
client.close()
except BakaShrotError:
pass
+147
View File
@@ -0,0 +1,147 @@
"""What goes over the wire, run by Tests/Python-Test.ps1.
Puts a TCP proxy between the client (BakaShrot_Client.dll, through
Interactors/Python/bakashrot.py) and the server, recording every byte, then
checks that:
- a pushed message, the client's identity and its topic never show up in
plain text, either way, handshake included;
- the message still makes it through and back;
- a byte flipped by the proxy after the handshake drops the connection;
- a client given another server's public key can't connect.
Usage: wire_check.py <BakaShrot_Client.dll> <client.ini> <proxy port> <other public key>
Exits with 0 if every check passed, 1 otherwise.
"""
import os
import socket
import sys
import threading
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "Interactors", "Python"))
from bakashrot import BakaShrotError, Client # noqa: E402
dll_path, ini_path, proxy_port, other_key = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4]
fails = 0
def check(what, ok, detail=""):
global fails
print(("PASS " if ok else "FAIL ") + what)
if detail:
print(" -> " + detail)
if not ok:
fails += 1
class Proxy:
"""Forwards one connection at a time to the server, keeping what passed.
tamper: flips a bit in the next chunk the client sends."""
def __init__(self, listen_port, server_host, server_port):
self.server = (server_host, server_port)
self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.listener.bind(("127.0.0.1", listen_port))
self.listener.listen(4)
self.to_server = bytearray()
self.to_client = bytearray()
self.tamper = False
threading.Thread(target=self._accept, daemon=True).start()
def _accept(self):
while True:
try:
client, _ = self.listener.accept()
except OSError:
return
upstream = socket.create_connection(self.server)
threading.Thread(target=self._pump, args=(client, upstream, True), daemon=True).start()
threading.Thread(target=self._pump, args=(upstream, client, False), daemon=True).start()
def _pump(self, source, target, from_client):
try:
while True:
data = source.recv(65536)
if not data:
break
data = bytearray(data)
if from_client and self.tamper:
self.tamper = False
data[-1] ^= 0x01
(self.to_server if from_client else self.to_client).extend(data)
target.sendall(data)
except OSError:
pass
for s in (source, target):
try:
s.shutdown(socket.SHUT_RDWR)
except OSError:
pass
s.close()
base = Client.from_ini(ini_path, dll_path)
proxy = Proxy(proxy_port, base.host, base.port)
marker = "wire-marker-7f3a91"
# The client's DefaultTopic in Python-Test.ps1's server config: its pushes
# land there, and it reads them back from there.
topic = "logs"
client = Client(base.private_key, base.public_key, base.server_public_key, base.node,
"127.0.0.1", proxy_port, dll_path)
# Through the proxy, all of it recorded.
try:
client.connect()
message_id = client.push({"note": marker})
latest = client.latest(topic, base.node)
check("Pushed and read back through the proxy", latest is not None and marker in latest.data,
latest.data if latest else "nothing")
pages = client.get_messages(topic, base.node, after=message_id - 1, limit=10)
check("Read as a run of messages too", any(marker in m.data for m in pages.messages))
client.close()
except BakaShrotError as error:
check("Pushed and read back through the proxy", False, str(error))
wire_up, wire_down = bytes(proxy.to_server), bytes(proxy.to_client)
check("Something went through both ways", len(wire_up) > 200 and len(wire_down) > 200,
f"{len(wire_up)} bytes up, {len(wire_down)} down")
for needle in (marker, str(base.node), topic, base.public_key):
shown = needle.encode("utf-8")
check(f"'{needle[:20]}' never in plain text on the wire", shown not in wire_up and shown not in wire_down)
# A bit flipped after the handshake: the server drops the connection.
try:
client.connect()
proxy.tamper = True
try:
client.push({"note": "tampered"})
check("A tampered request drops the connection", False, "the push went through")
except BakaShrotError as error:
check("A tampered request drops the connection", not client.connected, str(error))
client.close()
except BakaShrotError as error:
check("A tampered request drops the connection", False, "couldn't connect: " + str(error))
# Another server's key: the server can't open the Hello, nor sign for it.
impostor = Client(base.private_key, base.public_key, other_key, base.node,
base.host, base.port, dll_path)
try:
impostor.connect()
check("Another server's public key can't connect", False, "it connected")
impostor.close()
except BakaShrotError as error:
check("Another server's public key can't connect", True, str(error))
# And the right one still can, straight to the server.
try:
base.connect()
check("The right key still connects", base.connected)
base.close()
except BakaShrotError as error:
check("The right key still connects", False, str(error))
print()
print("All checks passed" if not fails else f"{fails} check(s) failed")
sys.exit(1 if fails else 0)