358 lines
14 KiB
Ziran
358 lines
14 KiB
Ziran
// Protocol v6 sync orchestration. The host provisions and stores device keys;
|
|
// this module signs the Mesh wire messages and sends them through Client.
|
|
#import "mesh_client/client"
|
|
#import "mesh_client/auth"
|
|
#import "mesh_client/transaction"
|
|
#import "mesh_client/wire"
|
|
#import "net_http"
|
|
#import "text_buffer"
|
|
#import "mesh_client/url"
|
|
#import "c_string"
|
|
#import "json_scan"
|
|
|
|
RandomNonce :: #type (context: *void, output: []u8) -> bool #c_call;
|
|
|
|
Device :: struct {
|
|
key_id: string
|
|
public_key_hex: string
|
|
signing_context: *void
|
|
signer: SignMessage
|
|
}
|
|
|
|
RegistrationCurrent :: (client: Client, session: *Session, device: Device, now: s64) -> bool {
|
|
if session == null || now < 0 || session.registration.expires_at <= now ||
|
|
session.registration.expires_at - now > 3600 {
|
|
return false
|
|
}
|
|
server: [512]u8
|
|
cached := *session.registration
|
|
return NormalizeUrl(client.server_url, server[:]) &&
|
|
TextUntilNul(server[:]) == TextUntilNul(cached.server[:]) &&
|
|
client.identity.account_id == TextUntilNul(cached.account[:]) &&
|
|
client.app_id == TextUntilNul(cached.app[:]) &&
|
|
client.identity.client_id == TextUntilNul(cached.client[:]) &&
|
|
device.key_id == TextUntilNul(cached.device[:]) &&
|
|
device.public_key_hex == TextUntilNul(cached.public_key[:])
|
|
}
|
|
|
|
RememberRegistration :: (client: Client, session: *Session, device: Device, now: s64) {
|
|
if session == null {
|
|
return
|
|
}
|
|
session.registration = Registration.{}
|
|
cached := *session.registration
|
|
if now < 0 || now > 9007199254740991 - 3600 ||
|
|
!NormalizeUrl(client.server_url, cached.server[:]) ||
|
|
!CopyCString(client.identity.account_id, cached.account[:]) ||
|
|
!CopyCString(client.app_id, cached.app[:]) ||
|
|
!CopyCString(client.identity.client_id, cached.client[:]) ||
|
|
!CopyCString(device.key_id, cached.device[:]) ||
|
|
!CopyCString(device.public_key_hex, cached.public_key[:]) {
|
|
session.registration = Registration.{}
|
|
return
|
|
}
|
|
cached.expires_at = now + 3600
|
|
}
|
|
|
|
MissingRegisteredDevice :: (status: s32, response: string) -> bool {
|
|
error: [128]u8
|
|
return status == 401 && ValidJson(response) &&
|
|
ReadStringText(response, FieldAt(response, 0, "error"), error[:]) >= 0 &&
|
|
TextUntilNul(error[:]) == "device key not registered"
|
|
}
|
|
|
|
ReplayedSyncTransaction :: (status: s32, response: string) -> bool {
|
|
error: [128]u8
|
|
return status == 409 && ValidJson(response) &&
|
|
ReadStringText(response, FieldAt(response, 0, "error"), error[:]) >= 0 &&
|
|
TextUntilNul(error[:]) == "signed transaction replay"
|
|
}
|
|
|
|
// Apps may persist this public hint alongside their bearer session. Cache
|
|
// readers validate every scope again before it can skip a registration.
|
|
WriteRegistration :: (registration: *Registration, output: []u8) -> bool {
|
|
writer := Writer.{.output = output, .valid = true}
|
|
writer = WriteByte(writer, 123)
|
|
names: [6]string = .["server", "account", "app", "client", "device", "public_key"]
|
|
values: [6]string = .[TextUntilNul(registration.server[:]), TextUntilNul(registration.account[:]),
|
|
TextUntilNul(registration.app[:]), TextUntilNul(registration.client[:]),
|
|
TextUntilNul(registration.device[:]), TextUntilNul(registration.public_key[:])]
|
|
for name, index: names {
|
|
writer = AppendJsonQuoted(writer, name)
|
|
writer = WriteByte(writer, 58)
|
|
writer = AppendJsonQuoted(writer, values[index])
|
|
writer = WriteByte(writer, 44)
|
|
}
|
|
writer = WriteText(writer, "\"expires_at\":")
|
|
writer = WriteDecimal(writer, registration.expires_at)
|
|
writer = WriteByte(writer, 125)
|
|
return writer.valid
|
|
}
|
|
|
|
ReadRegistration :: (text: string, registration: *Registration) -> bool {
|
|
registration.* = Registration.{}
|
|
candidate: Registration
|
|
if !FieldText(text, "server", candidate.server[:]) ||
|
|
!FieldText(text, "account", candidate.account[:]) ||
|
|
!FieldText(text, "app", candidate.app[:]) ||
|
|
!FieldText(text, "client", candidate.client[:]) ||
|
|
!FieldText(text, "device", candidate.device[:]) ||
|
|
!FieldText(text, "public_key", candidate.public_key[:]) {
|
|
return false
|
|
}
|
|
candidate.expires_at = FieldNumber(text, "expires_at", 0)
|
|
if candidate.expires_at <= 0 {
|
|
return false
|
|
}
|
|
registration.* = candidate
|
|
return true
|
|
}
|
|
|
|
SignatureHex :: (value: string, length: s64) -> bool {
|
|
if cast(s64)value.count != length {
|
|
return false
|
|
}
|
|
index: s64 = 0
|
|
while index < length {
|
|
byte := value[index]
|
|
if !((byte >= cast(u8)48 && byte <= cast(u8)57) ||
|
|
(byte >= cast(u8)65 && byte <= cast(u8)70) ||
|
|
(byte >= cast(u8)97 && byte <= cast(u8)102)) {
|
|
return false
|
|
}
|
|
index += 1
|
|
}
|
|
return true
|
|
}
|
|
|
|
ServerNow :: (session: *Session, now: s64) -> s64 {
|
|
if session.server_time <= 0 || session.login_local_time <= 0 ||
|
|
now < session.login_local_time ||
|
|
now - session.login_local_time > 86400 {
|
|
return now
|
|
}
|
|
return session.server_time + now - session.login_local_time
|
|
}
|
|
|
|
CreateNonce :: (random_context: *void, random: RandomNonce,
|
|
output: []u8) -> bool {
|
|
if output.count < 65 {
|
|
return false
|
|
}
|
|
output[0] = cast(u8)0
|
|
return random(random_context, output) &&
|
|
Hex64(TextUntilNul(output[:]))
|
|
}
|
|
|
|
#scope_export
|
|
#program_export
|
|
RegisterDevice :: (client: Client, session: *Session,
|
|
device: Device, now: s64, random_context: *void,
|
|
random: RandomNonce) -> AuthResult {
|
|
ready := EnsureSession(client, session, now)
|
|
if ready != cast(AuthResult)AuthResult.AUTH_OK {
|
|
return ready
|
|
}
|
|
body: [6144]u8
|
|
prepared := PrepareDeviceRegistration(client, session, device, now,
|
|
random_context, random, body[:])
|
|
if prepared != cast(AuthResult)AuthResult.AUTH_OK {
|
|
return prepared
|
|
}
|
|
response: [2048]u8
|
|
status: s32 = 0
|
|
result := BearerRequest(client, session, now, "POST",
|
|
"/api/v1/account/devices", TextUntilNul(body[:]),
|
|
response[:], *status)
|
|
if result == cast(AuthResult)AuthResult.AUTH_OK {
|
|
RememberRegistration(client, session, device, now)
|
|
}
|
|
return result
|
|
}
|
|
|
|
#scope_export
|
|
#program_export
|
|
Sync :: (client: Client, session: *Session, device: Device,
|
|
now: s64, random_context: *void, random: RandomNonce,
|
|
body: string, output: []u8, status: *s32) -> AuthResult {
|
|
if output.count == 0 || status == null || body.count == 0 {
|
|
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
|
|
}
|
|
output[0] = cast(u8)0
|
|
status.* = 0
|
|
ready := EnsureSession(client, session, now)
|
|
if ready != cast(AuthResult)AuthResult.AUTH_OK {
|
|
return ready
|
|
}
|
|
cached := RegistrationCurrent(client, session, device, now)
|
|
registered := cached
|
|
registration_retried := false
|
|
for attempt: cast(s32)0..2 {
|
|
if !registered {
|
|
registration_result := RegisterDevice(client, session, device, now, random_context, random)
|
|
if registration_result != cast(AuthResult)AuthResult.AUTH_OK {
|
|
return registration_result
|
|
}
|
|
registered = true
|
|
}
|
|
transaction_header: [8192]u8
|
|
prepared := PrepareSyncHeader(client, session, device, now,
|
|
random_context, random, body, transaction_header[:])
|
|
if prepared != cast(AuthResult)AuthResult.AUTH_OK {
|
|
return prepared
|
|
}
|
|
extra: [1]HttpHeader
|
|
extra[0].name = "X-Daochi-Tx"
|
|
extra[0].value = TextUntilNul(transaction_header[:])
|
|
result := BearerRequestWithHeaders(client, session, now,
|
|
"POST", "/api/v1/sync", body, output, status, extra[:])
|
|
if result == cast(AuthResult)AuthResult.AUTH_OK {
|
|
RememberRegistration(client, session, device, now)
|
|
return result
|
|
}
|
|
if attempt < 2 && ReplayedSyncTransaction(status.*, TextUntilNul(output)) {
|
|
// A transport may transparently retry a reused connection after
|
|
// the original sync committed. Keep replay rejection and recover
|
|
// the idempotent sync with fresh account/device signatures.
|
|
continue
|
|
}
|
|
if !cached || registration_retried || attempt >= 2 ||
|
|
!MissingRegisteredDevice(status.*, TextUntilNul(output)) {
|
|
return result
|
|
}
|
|
session.registration = Registration.{}
|
|
registered = false
|
|
registration_retried = true
|
|
}
|
|
return cast(AuthResult)AuthResult.AUTH_REQUEST_FAILED
|
|
}
|
|
|
|
// Shared request preparation for blocking and frame-driven transports.
|
|
#scope_export
|
|
PrepareDeviceRegistration :: (client: Client, session: *Session,
|
|
device: Device, now: s64, random_context: *void,
|
|
random: RandomNonce, body: []u8) -> AuthResult {
|
|
if !Hex64(device.key_id) ||
|
|
!Hex64(device.public_key_hex) {
|
|
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
|
|
}
|
|
nonce: [65]u8
|
|
if !CreateNonce(random_context, random, nonce[:]) {
|
|
return cast(AuthResult)AuthResult.AUTH_SIGN_FAILED
|
|
}
|
|
server_now := ServerNow(session, now)
|
|
if server_now <= 0 || server_now > 9007199254740691 {
|
|
return cast(AuthResult)AuthResult.AUTH_SIGN_FAILED
|
|
}
|
|
registration: DeviceRegistration
|
|
registration.account_id = client.identity.account_id
|
|
registration.app_id = client.app_id
|
|
registration.device_key_id = device.key_id
|
|
registration.client_id = client.identity.client_id
|
|
registration.public_key_hex = device.public_key_hex
|
|
registration.nonce = TextUntilNul(nonce[:])
|
|
registration.expires_at = server_now + 300
|
|
message: [1024]u8
|
|
if !BuildDeviceRegistrationMessage(registration, message[:]) {
|
|
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
|
|
}
|
|
account_signature: [4841]u8
|
|
if !client.signer(client.identity.signing_context,
|
|
TextUntilNul(message[:]), account_signature[:]) ||
|
|
!SignatureHex(TextUntilNul(account_signature[:]), 4840) {
|
|
return cast(AuthResult)AuthResult.AUTH_SIGN_FAILED
|
|
}
|
|
if !BuildDeviceRegistrationBody(registration,
|
|
TextUntilNul(account_signature[:]), body) {
|
|
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
|
|
}
|
|
return cast(AuthResult)AuthResult.AUTH_OK
|
|
}
|
|
|
|
#scope_export
|
|
PrepareSyncHeader :: (client: Client, session: *Session, device: Device,
|
|
now: s64, random_context: *void, random: RandomNonce,
|
|
body: string, transaction_header: []u8) -> AuthResult {
|
|
return PrepareRequestHeader(client, session, device, now,
|
|
random_context, random, "POST", "/api/v1/sync", body,
|
|
transaction_header)
|
|
}
|
|
|
|
// Binary bodies and empty GET/HEAD bodies retain their exact byte length.
|
|
// Both platform hosts and sync orchestration use the same signed preparation.
|
|
#scope_export
|
|
PrepareRequestHeader :: (client: Client, session: *Session, device: Device,
|
|
now: s64, random_context: *void, random: RandomNonce,
|
|
method: string, path: string, body: string,
|
|
transaction_header: []u8) -> AuthResult {
|
|
if transaction_header.count == 0 {
|
|
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
|
|
}
|
|
transaction_header[0] = cast(u8)0
|
|
if session == null || random == null || client.digest == null {
|
|
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
|
|
}
|
|
tx_id: [65]u8
|
|
nonce: [65]u8
|
|
body_hash: [65]u8
|
|
if !CreateNonce(random_context, random, tx_id[:]) ||
|
|
!CreateNonce(random_context, random, nonce[:]) ||
|
|
!client.digest(body, body_hash[:]) ||
|
|
!Hex64(TextUntilNul(body_hash[:])) {
|
|
return cast(AuthResult)AuthResult.AUTH_SIGN_FAILED
|
|
}
|
|
server_now := ServerNow(session, now)
|
|
if server_now <= 0 || server_now > 9007199254740691 {
|
|
return cast(AuthResult)AuthResult.AUTH_SIGN_FAILED
|
|
}
|
|
transaction: SyncTransaction
|
|
transaction.account_id = client.identity.account_id
|
|
transaction.app_id = client.app_id
|
|
transaction.device_key_id = device.key_id
|
|
transaction.tx_id = TextUntilNul(tx_id[:])
|
|
transaction.nonce = TextUntilNul(nonce[:])
|
|
transaction.body_sha256_hex = TextUntilNul(body_hash[:])
|
|
transaction.expires_at = server_now + 300
|
|
return SignTransactionHeader(client, device, transaction, method, path,
|
|
transaction_header)
|
|
}
|
|
|
|
// Hosts that stream and hash a body themselves supply the finished digest and
|
|
// expiration. The client owns the account/device signatures and wire format.
|
|
#scope_export
|
|
SignTransactionHeader :: (client: Client, device: Device,
|
|
transaction: SyncTransaction, method: string, path: string,
|
|
transaction_header: []u8) -> AuthResult {
|
|
if transaction_header.count == 0 {
|
|
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
|
|
}
|
|
transaction_header[0] = cast(u8)0
|
|
if client.signer == null || device.signer == null ||
|
|
transaction.account_id != client.identity.account_id ||
|
|
transaction.app_id != client.app_id ||
|
|
transaction.device_key_id != device.key_id {
|
|
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
|
|
}
|
|
message: [4096]u8
|
|
if !BuildTransactionMessage(transaction, method, path, message[:]) {
|
|
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
|
|
}
|
|
account_signature: [4841]u8
|
|
device_signature: [129]u8
|
|
if !client.signer(client.identity.signing_context,
|
|
TextUntilNul(message[:]), account_signature[:]) ||
|
|
!SignatureHex(TextUntilNul(account_signature[:]), 4840) ||
|
|
!device.signer(device.signing_context,
|
|
TextUntilNul(message[:]), device_signature[:]) ||
|
|
!SignatureHex(TextUntilNul(device_signature[:]), 128) {
|
|
return cast(AuthResult)AuthResult.AUTH_SIGN_FAILED
|
|
}
|
|
if !BuildTransactionHeader(transaction, method, path,
|
|
TextUntilNul(account_signature[:]),
|
|
TextUntilNul(device_signature[:]),
|
|
transaction_header) {
|
|
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
|
|
}
|
|
return cast(AuthResult)AuthResult.AUTH_OK
|
|
}
|