Port signed-transaction authentication and device signature checks to Ziran
This commit is contained in:
1 parent
5244eb4859
commit
cfae9e0abc
25 files changed
+1324
-245
No files matched your search
@@ -0,0 +1,30 @@
|
||||
// Code generated by zi2go from account_keys.zi. DO NOT EDIT.
|
||||
package main
|
||||
|
||||
import sql "database/sql"
|
||||
|
||||
// #import go_types
|
||||
type AccountKeyResult struct {
|
||||
Value []uint8
|
||||
Found bool
|
||||
Error Error
|
||||
}
|
||||
|
||||
func AccountKeys_PublicKey(database *Database, context Context, accountID string) AccountKeyResult {
|
||||
var result AccountKeyResult = AccountKeyResult{}
|
||||
var key []uint8 = nil
|
||||
var value_0 *Row = (*sql.DB).QueryRowContext(database, context, "SELECT public_key FROM server_users WHERE user_id_hash=?1", accountID)
|
||||
row := value_0
|
||||
error := (*sql.Row).Scan(row, &(key))
|
||||
var value_1 Error = error
|
||||
if ErrorsGo_Is(value_1, SqlGo_NoRows()) {
|
||||
return result
|
||||
}
|
||||
if error != nil {
|
||||
result.Error = error
|
||||
return result
|
||||
}
|
||||
result.Value = key
|
||||
result.Found = true
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#import "go_types"
|
||||
ctx :: #import "context_go";
|
||||
sql :: #import "sql_go";
|
||||
errors :: #import "errors_go";
|
||||
go_sql :: #system_library "go:database/sql";
|
||||
|
||||
AccountKeyResult :: struct {
|
||||
value: []u8
|
||||
found: bool
|
||||
error: Error
|
||||
}
|
||||
|
||||
#scope_file
|
||||
Query :: (database: *sql.Database, context: ctx.Context, query: string, accountID: string) -> *sql.Row #foreign go_sql "(*DB).QueryRowContext";
|
||||
Scan :: (row: *sql.Row, key: *[]u8) -> Error #foreign go_sql "(*Row).Scan";
|
||||
|
||||
#scope_export
|
||||
PublicKey :: (database: *sql.Database, context: ctx.Context, accountID: string) -> AccountKeyResult {
|
||||
result: AccountKeyResult
|
||||
key: []u8
|
||||
row := Query(database, context, "SELECT public_key FROM server_users WHERE user_id_hash=?1", accountID)
|
||||
error := Scan(row, *key)
|
||||
if errors.Is(error, sql.NoRows()) {
|
||||
return result
|
||||
}
|
||||
if error != null {
|
||||
result.error = error
|
||||
return result
|
||||
}
|
||||
result.value = key
|
||||
result.found = true
|
||||
return result
|
||||
}
|
||||
+8
-25
@@ -265,26 +265,6 @@ ORDER BY asset_id,permission`, appID)
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) RecordSignedTx(ctx context.Context, tx SignedTxEnvelope) error {
|
||||
if _, err := s.db.ExecContext(ctx, `DELETE FROM server_signed_transactions WHERE expires_at<?1`, time.Now().Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO server_signed_transactions(account_id,tx_id,app_id,nonce,expires_at)
|
||||
VALUES(?1,?2,?3,?4,?5)`, tx.AccountID, tx.TxID, tx.AppID, tx.Nonce, tx.ExpiresAt)
|
||||
if err != nil && strings.Contains(err.Error(), "UNIQUE") {
|
||||
return errSignedTxReplay
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) ForgetSignedTx(ctx context.Context, tx SignedTxEnvelope) {
|
||||
_, _ = s.db.ExecContext(ctx, `
|
||||
DELETE FROM server_signed_transactions
|
||||
WHERE account_id=?1 AND tx_id=?2 AND app_id=?3 AND nonce=?4`,
|
||||
tx.AccountID, tx.TxID, tx.AppID, tx.Nonce)
|
||||
}
|
||||
|
||||
func (s *Store) AppTokenPermission(ctx context.Context, appID, assetID, permission string) (TokenPolicy, bool, error) {
|
||||
var policy TokenPolicy
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
@@ -351,7 +331,8 @@ func validateSignedAppRegistration(req SignedAppRegistrationRequest, nodePublicK
|
||||
if len(nodePublicKey) != ed25519.PublicKeySize {
|
||||
return nil, "", authError{status: http.StatusForbidden, message: "node registry approval unavailable"}
|
||||
}
|
||||
manifestBytes, err := canonicalJSON(req.Manifest)
|
||||
serialized := JsonGo_Marshal(req.Manifest)
|
||||
manifestBytes, err := serialized.Value, serialized.Error
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
@@ -361,7 +342,7 @@ func validateSignedAppRegistration(req SignedAppRegistrationRequest, nodePublicK
|
||||
if manifestSigField.Error != "" || len(manifestSig) != ed25519.SignatureSize {
|
||||
return nil, "", authError{status: http.StatusBadRequest, message: "invalid manifest signature"}
|
||||
}
|
||||
manifestMsg := append([]byte(daochiAppManifestContext+"\n"), manifestBytes...)
|
||||
manifestMsg := append([]byte(AppManifestContext+"\n"), manifestBytes...)
|
||||
if !Manifest_SignedByActiveKey(req.Manifest, manifestMsg, manifestSig, time.Now().Unix()) {
|
||||
return nil, "", authError{status: http.StatusUnauthorized, message: "manifest signature rejected"}
|
||||
}
|
||||
@@ -370,14 +351,15 @@ func validateSignedAppRegistration(req SignedAppRegistrationRequest, nodePublicK
|
||||
if approvalSigField.Error != "" || len(approvalSig) != ed25519.SignatureSize {
|
||||
return nil, "", authError{status: http.StatusBadRequest, message: "invalid approval signature"}
|
||||
}
|
||||
if !ed25519.Verify(nodePublicKey, []byte(Signing_AppApprovalMessage(daochiAppApprovalContext, req.Manifest.AppID, manifestHash)), approvalSig) {
|
||||
if !ed25519.Verify(nodePublicKey, []byte(Signing_AppApprovalMessage(AppApprovalContext, req.Manifest.AppID, manifestHash)), approvalSig) {
|
||||
return nil, "", authError{status: http.StatusUnauthorized, message: "node approval rejected"}
|
||||
}
|
||||
return manifestBytes, manifestHash, nil
|
||||
}
|
||||
|
||||
func manifestDigest(manifest AppManifest) (string, error) {
|
||||
data, err := canonicalJSON(manifest)
|
||||
serialized := JsonGo_Marshal(manifest)
|
||||
data, err := serialized.Value, serialized.Error
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -390,7 +372,8 @@ func formatAppManifestForTest(manifest AppManifest) ([]byte, string, error) {
|
||||
if problem := Manifest_Validate(manifest, time.Now().Unix()); problem != "" {
|
||||
return nil, "", errors.New(problem)
|
||||
}
|
||||
data, err := canonicalJSON(manifest)
|
||||
serialized := JsonGo_Marshal(manifest)
|
||||
data, err := serialized.Value, serialized.Error
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
+8
-6
@@ -607,7 +607,8 @@ func (s *Server) handleSignedAppGrant(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
grantBody, err := canonicalJSON(req.Grant)
|
||||
serialized := JsonGo_Marshal(req.Grant)
|
||||
grantBody, err := serialized.Value, serialized.Error
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid app grant")
|
||||
return
|
||||
@@ -620,14 +621,14 @@ func (s *Server) handleSignedAppGrant(w http.ResponseWriter, r *http.Request) {
|
||||
req.Tx.BodySHA256 = Signing_SHA256Hex(grantBody)
|
||||
}
|
||||
_ = body
|
||||
if err := s.verifySignedTx(r.Context(), r, grantBody, req.Tx, userID, req.Grant.TargetAppID); err != nil {
|
||||
if err := authenticationError(SignedTx_Verify(s.store.db, r.Context(), r, grantBody, req.Tx, userID, req.Grant.TargetAppID, s.verifier.Verify, errSignedTxReplay)); err != nil {
|
||||
s.writeAuthError(w, err)
|
||||
return
|
||||
}
|
||||
created := false
|
||||
defer func() {
|
||||
if !created {
|
||||
s.store.ForgetSignedTx(r.Context(), req.Tx)
|
||||
SignedTx_Forget(s.store.db, r.Context(), req.Tx)
|
||||
}
|
||||
}()
|
||||
grant, err := s.store.CreateAppGrant(r.Context(), userID, req.Grant)
|
||||
@@ -682,19 +683,20 @@ func (s *Server) handleAppRecords(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, "invalid app records query")
|
||||
return
|
||||
}
|
||||
tx, err := readSignedTxHeader(r)
|
||||
header := SignedTx_ReadHeader(r)
|
||||
tx, err := header.Value, authenticationError(header.Authentication)
|
||||
if err != nil {
|
||||
s.writeAuthError(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.verifySignedTx(r.Context(), r, nil, tx, userID, targetAppID); err != nil {
|
||||
if err := authenticationError(SignedTx_Verify(s.store.db, r.Context(), r, nil, tx, userID, targetAppID, s.verifier.Verify, errSignedTxReplay)); err != nil {
|
||||
s.writeAuthError(w, err)
|
||||
return
|
||||
}
|
||||
readCompleted := false
|
||||
defer func() {
|
||||
if !readCompleted {
|
||||
s.store.ForgetSignedTx(r.Context(), tx)
|
||||
SignedTx_Forget(s.store.db, r.Context(), tx)
|
||||
}
|
||||
}()
|
||||
records, err := s.store.AuthorizedAppRecords(r.Context(), userID, sourceAppID, targetAppID, collectionPrefix)
|
||||
|
||||
+2
-2
@@ -68,8 +68,8 @@ func TestInbeReleasedAndCurrentScopesRemainValid(t *testing.T) {
|
||||
|
||||
func TestSignedTransactionContextIsNotCallerDefined(t *testing.T) {
|
||||
tx := SignedTxEnvelope{ProtocolVersion: 6, SignatureContext: "attacker-context"}
|
||||
message := Transaction_CanonicalMessage(daochiTxContext, tx)
|
||||
if !strings.HasPrefix(message, daochiTxContext+"\n") || strings.Contains(message, "attacker-context") {
|
||||
message := Transaction_CanonicalMessage(TransactionContext, tx)
|
||||
if !strings.HasPrefix(message, TransactionContext+"\n") || strings.Contains(message, "attacker-context") {
|
||||
t.Fatalf("canonical transaction context was caller-controlled: %q", message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Code generated by zi2go from authentication.zi. DO NOT EDIT.
|
||||
package main
|
||||
|
||||
// #import go_types
|
||||
type VerifySignature func([]uint8, []uint8, []uint8) bool
|
||||
|
||||
type AuthenticationResult struct {
|
||||
Status int
|
||||
Message string
|
||||
Error Error
|
||||
}
|
||||
|
||||
func Authentication_Failure(status int, message string) AuthenticationResult {
|
||||
var result AuthenticationResult = AuthenticationResult{}
|
||||
result.Status = status
|
||||
result.Message = message
|
||||
return result
|
||||
}
|
||||
|
||||
func Authentication_NativeFailure(error Error) AuthenticationResult {
|
||||
var result AuthenticationResult = AuthenticationResult{}
|
||||
result.Error = error
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#import "go_types"
|
||||
|
||||
VerifySignature :: #type (publicKey: []u8, message: []u8, signature: []u8) -> bool;
|
||||
|
||||
AuthenticationResult :: struct {
|
||||
status: isize
|
||||
message: string
|
||||
error: Error
|
||||
}
|
||||
|
||||
Failure :: (status: isize, message: string) -> AuthenticationResult {
|
||||
result: AuthenticationResult
|
||||
result.status = status
|
||||
result.message = message
|
||||
return result
|
||||
}
|
||||
|
||||
NativeFailure :: (error: Error) -> AuthenticationResult {
|
||||
result: AuthenticationResult
|
||||
result.error = error
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package main
|
||||
|
||||
// Convert the checked Ziran result at the existing Go HTTP error boundary.
|
||||
func authenticationError(result AuthenticationResult) error {
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.Status != 0 {
|
||||
return authError{status: result.Status, message: result.Message}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+2
-49
@@ -1,58 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (s *Server) verifyDeviceRegistration(ctx context.Context, accountID string, request DeviceRegistrationRequest) error {
|
||||
if !DeviceKeys_ValidRegistration(request) {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid device registration"}
|
||||
}
|
||||
accountKey, found, err := s.store.PublicKey(ctx, accountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return authError{status: http.StatusUnauthorized, message: "sync account not found"}
|
||||
}
|
||||
signatureField := Codec_DecodeBinaryField(request.Signature)
|
||||
signature := []byte(signatureField.Value)
|
||||
if signatureField.Error != "" || len(signature) != mlDSA44SignatureSize {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid device registration signature"}
|
||||
}
|
||||
message := DeviceKeys_RegistrationMessage(accountID, request)
|
||||
if !s.verifier.Verify(accountKey, message, signature) {
|
||||
return authError{status: http.StatusUnauthorized, message: "device registration rejected"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) verifyDeviceRevocation(ctx context.Context, accountID string, request DeviceRevocationRequest) error {
|
||||
if !Identity_ValidNamespace(request.AppID) || !Identity_ValidClientID(request.KeyID) ||
|
||||
!Identity_ValidClientID(request.Nonce) || !DeviceKeys_ValidExpiry(request.ExpiresAt) {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid device revocation"}
|
||||
}
|
||||
accountKey, found, err := s.store.PublicKey(ctx, accountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return authError{status: http.StatusUnauthorized, message: "sync account not found"}
|
||||
}
|
||||
signatureField := Codec_DecodeBinaryField(request.Signature)
|
||||
signature := []byte(signatureField.Value)
|
||||
if signatureField.Error != "" || len(signature) != mlDSA44SignatureSize {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid device revocation signature"}
|
||||
}
|
||||
if !s.verifier.Verify(accountKey, DeviceKeys_RevocationMessage(accountID, request), signature) {
|
||||
return authError{status: http.StatusUnauthorized, message: "device revocation rejected"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) handleAccountDevices(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := s.bearerUser(w, r)
|
||||
if !ok {
|
||||
@@ -83,7 +36,7 @@ func (s *Server) handleAccountDevices(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
DeviceKeys_NormalizeRegistration(&request)
|
||||
if err := s.verifyDeviceRegistration(r.Context(), accountID, request); err != nil {
|
||||
if err := authenticationError(DeviceKeys_VerifyRegistration(s.store.db, r.Context(), accountID, request, s.verifier.Verify)); err != nil {
|
||||
s.writeAuthError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -117,7 +70,7 @@ func (s *Server) handleDeviceRevocation(w http.ResponseWriter, r *http.Request,
|
||||
return
|
||||
}
|
||||
DeviceKeys_NormalizeRevocation(&request)
|
||||
if err := s.verifyDeviceRevocation(r.Context(), accountID, request); err != nil {
|
||||
if err := authenticationError(DeviceKeys_VerifyRevocation(s.store.db, r.Context(), accountID, request, s.verifier.Verify)); err != nil {
|
||||
s.writeAuthError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
+85
-22
@@ -50,17 +50,17 @@ type DeviceListResult struct {
|
||||
Error Error
|
||||
}
|
||||
|
||||
type zir_1b627dc0e6db542b_TransactionResult struct {
|
||||
type zir_7e7cd09519a1fca6_TransactionResult struct {
|
||||
Value *Transaction
|
||||
Error Error
|
||||
}
|
||||
|
||||
type zir_9f77619cbb1e2ba7_ExecResult struct {
|
||||
type zir_0291b470ede4d422_ExecResult struct {
|
||||
Value Result
|
||||
Error Error
|
||||
}
|
||||
|
||||
type zir_238c45788f610323_RowsResult struct {
|
||||
type zir_a74db72b643e677e_RowsResult struct {
|
||||
Value *Rows
|
||||
Error Error
|
||||
}
|
||||
@@ -76,44 +76,44 @@ func DeviceKeys_DecodeHex(Value string) KeyResult {
|
||||
return result
|
||||
}
|
||||
|
||||
func DeviceKeys_Begin(Database *Database, Context Context, Options *TransactionOptions) zir_1b627dc0e6db542b_TransactionResult {
|
||||
var result zir_1b627dc0e6db542b_TransactionResult
|
||||
func DeviceKeys_Begin(Database *Database, Context Context, Options *TransactionOptions) zir_7e7cd09519a1fca6_TransactionResult {
|
||||
var result zir_7e7cd09519a1fca6_TransactionResult
|
||||
result.Value, result.Error = (*sql.DB).BeginTx(Database, Context, Options)
|
||||
return result
|
||||
}
|
||||
|
||||
func DeviceKeys_DeleteNonces(Transaction *Transaction, Context Context, Query string, Cutoff string) zir_9f77619cbb1e2ba7_ExecResult {
|
||||
var result zir_9f77619cbb1e2ba7_ExecResult
|
||||
func DeviceKeys_DeleteNonces(Transaction *Transaction, Context Context, Query string, Cutoff string) zir_0291b470ede4d422_ExecResult {
|
||||
var result zir_0291b470ede4d422_ExecResult
|
||||
result.Value, result.Error = (*sql.Tx).ExecContext(Transaction, Context, Query, Cutoff)
|
||||
return result
|
||||
}
|
||||
|
||||
func DeviceKeys_InsertNonce(Transaction *Transaction, Context Context, Query string, AccountID string, Nonce string, Created string) zir_9f77619cbb1e2ba7_ExecResult {
|
||||
var result zir_9f77619cbb1e2ba7_ExecResult
|
||||
func DeviceKeys_InsertNonce(Transaction *Transaction, Context Context, Query string, AccountID string, Nonce string, Created string) zir_0291b470ede4d422_ExecResult {
|
||||
var result zir_0291b470ede4d422_ExecResult
|
||||
result.Value, result.Error = (*sql.Tx).ExecContext(Transaction, Context, Query, AccountID, Nonce, Created)
|
||||
return result
|
||||
}
|
||||
|
||||
func DeviceKeys_InsertDevice(Transaction *Transaction, Context Context, Query string, AccountID string, AppID string, KeyID string, ClientID string, Key string, Created string) zir_9f77619cbb1e2ba7_ExecResult {
|
||||
var result zir_9f77619cbb1e2ba7_ExecResult
|
||||
func DeviceKeys_InsertDevice(Transaction *Transaction, Context Context, Query string, AccountID string, AppID string, KeyID string, ClientID string, Key string, Created string) zir_0291b470ede4d422_ExecResult {
|
||||
var result zir_0291b470ede4d422_ExecResult
|
||||
result.Value, result.Error = (*sql.Tx).ExecContext(Transaction, Context, Query, AccountID, AppID, KeyID, ClientID, Key, Created)
|
||||
return result
|
||||
}
|
||||
|
||||
func DeviceKeys_RevokeDevice(Transaction *Transaction, Context Context, Query string, AccountID string, AppID string, KeyID string, Revoked string) zir_9f77619cbb1e2ba7_ExecResult {
|
||||
var result zir_9f77619cbb1e2ba7_ExecResult
|
||||
func DeviceKeys_RevokeDevice(Transaction *Transaction, Context Context, Query string, AccountID string, AppID string, KeyID string, Revoked string) zir_0291b470ede4d422_ExecResult {
|
||||
var result zir_0291b470ede4d422_ExecResult
|
||||
result.Value, result.Error = (*sql.Tx).ExecContext(Transaction, Context, Query, AccountID, AppID, KeyID, Revoked)
|
||||
return result
|
||||
}
|
||||
|
||||
func DeviceKeys_TouchDevice(Database *Database, Context Context, Query string, AccountID string, AppID string, KeyID string, Used string) zir_9f77619cbb1e2ba7_ExecResult {
|
||||
var result zir_9f77619cbb1e2ba7_ExecResult
|
||||
func DeviceKeys_TouchDevice(Database *Database, Context Context, Query string, AccountID string, AppID string, KeyID string, Used string) zir_0291b470ede4d422_ExecResult {
|
||||
var result zir_0291b470ede4d422_ExecResult
|
||||
result.Value, result.Error = (*sql.DB).ExecContext(Database, Context, Query, AccountID, AppID, KeyID, Used)
|
||||
return result
|
||||
}
|
||||
|
||||
func DeviceKeys_QueryDevices(Database *Database, Context Context, Query string, AccountID string) zir_238c45788f610323_RowsResult {
|
||||
var result zir_238c45788f610323_RowsResult
|
||||
func DeviceKeys_QueryDevices(Database *Database, Context Context, Query string, AccountID string) zir_a74db72b643e677e_RowsResult {
|
||||
var result zir_a74db72b643e677e_RowsResult
|
||||
result.Value, result.Error = (*sql.DB).QueryContext(Database, Context, Query, AccountID)
|
||||
return result
|
||||
}
|
||||
@@ -128,12 +128,12 @@ const ListSQL = "\nSELECT account_id,app_id,device_key_id,client_id,public_key,c
|
||||
|
||||
func DeviceKeys_RecordNonce(transaction *Transaction, context Context, accountID string, nonce string, replay Error) Error {
|
||||
cutoff := Timestamp_CanonicalTimestamp(TimeGo_Add(TimeGo_Now(), Duration(-1800000000000)))
|
||||
var value_0 zir_9f77619cbb1e2ba7_ExecResult = DeviceKeys_DeleteNonces(transaction, context, "DELETE FROM server_device_registration_nonces WHERE created_at<?1", cutoff)
|
||||
var value_0 zir_0291b470ede4d422_ExecResult = DeviceKeys_DeleteNonces(transaction, context, "DELETE FROM server_device_registration_nonces WHERE created_at<?1", cutoff)
|
||||
deleted := value_0
|
||||
if deleted.Error != nil {
|
||||
return deleted.Error
|
||||
}
|
||||
var value_1 zir_9f77619cbb1e2ba7_ExecResult = DeviceKeys_InsertNonce(transaction, context, "INSERT INTO server_device_registration_nonces(account_id,nonce,created_at) VALUES(?1,?2,?3)", accountID, nonce, Timestamp_CanonicalNow())
|
||||
var value_1 zir_0291b470ede4d422_ExecResult = DeviceKeys_InsertNonce(transaction, context, "INSERT INTO server_device_registration_nonces(account_id,nonce,created_at) VALUES(?1,?2,?3)", accountID, nonce, Timestamp_CanonicalNow())
|
||||
inserted := value_1
|
||||
var value_2 bool = inserted.Error != nil
|
||||
var value_3 bool = value_2
|
||||
@@ -227,6 +227,69 @@ func DeviceKeys_ValidRegistration(request DeviceRegistrationRequest) bool {
|
||||
return DeviceKeys_ValidExpiry(request.ExpiresAt)
|
||||
}
|
||||
|
||||
func DeviceKeys_VerifyRegistration(database *Database, context Context, accountID string, request DeviceRegistrationRequest, verifySignature VerifySignature) AuthenticationResult {
|
||||
var value_0 bool = DeviceKeys_ValidRegistration(request)
|
||||
if !value_0 {
|
||||
return Authentication_Failure(int(400), "invalid device registration")
|
||||
}
|
||||
account := AccountKeys_PublicKey(database, context, accountID)
|
||||
if account.Error != nil {
|
||||
return Authentication_NativeFailure(account.Error)
|
||||
}
|
||||
if !account.Found {
|
||||
return Authentication_Failure(int(401), "sync account not found")
|
||||
}
|
||||
signature := Codec_DecodeBinaryField(request.Signature)
|
||||
if signature.Error != "" || int64(len(signature.Value)) != 2420 {
|
||||
return Authentication_Failure(int(400), "invalid device registration signature")
|
||||
}
|
||||
var value_1 VerifySignature = verifySignature
|
||||
var value_2 bool = value_1(account.Value, DeviceKeys_RegistrationMessage(accountID, request), TextGo_ToBytes(signature.Value))
|
||||
if !value_2 {
|
||||
return Authentication_Failure(int(401), "device registration rejected")
|
||||
}
|
||||
return Authentication_NativeFailure(nil)
|
||||
}
|
||||
|
||||
func DeviceKeys_VerifyRevocation(database *Database, context Context, accountID string, request DeviceRevocationRequest, verifySignature VerifySignature) AuthenticationResult {
|
||||
var value_0 bool = Identity_ValidNamespace(request.AppID)
|
||||
var value_1 bool = !value_0
|
||||
if !value_1 {
|
||||
var value_2 bool = Identity_ValidClientID(request.KeyID)
|
||||
value_1 = !value_2
|
||||
}
|
||||
var value_3 bool = value_1
|
||||
if !value_3 {
|
||||
var value_4 bool = Identity_ValidClientID(request.Nonce)
|
||||
value_3 = !value_4
|
||||
}
|
||||
var value_5 bool = value_3
|
||||
if !value_5 {
|
||||
var value_6 bool = DeviceKeys_ValidExpiry(request.ExpiresAt)
|
||||
value_5 = !value_6
|
||||
}
|
||||
if value_5 {
|
||||
return Authentication_Failure(int(400), "invalid device revocation")
|
||||
}
|
||||
account := AccountKeys_PublicKey(database, context, accountID)
|
||||
if account.Error != nil {
|
||||
return Authentication_NativeFailure(account.Error)
|
||||
}
|
||||
if !account.Found {
|
||||
return Authentication_Failure(int(401), "sync account not found")
|
||||
}
|
||||
signature := Codec_DecodeBinaryField(request.Signature)
|
||||
if signature.Error != "" || int64(len(signature.Value)) != 2420 {
|
||||
return Authentication_Failure(int(400), "invalid device revocation signature")
|
||||
}
|
||||
var value_7 VerifySignature = verifySignature
|
||||
var value_8 bool = value_7(account.Value, DeviceKeys_RevocationMessage(accountID, request), TextGo_ToBytes(signature.Value))
|
||||
if !value_8 {
|
||||
return Authentication_Failure(int(401), "device revocation rejected")
|
||||
}
|
||||
return Authentication_NativeFailure(nil)
|
||||
}
|
||||
|
||||
func DeviceKeys_Register(database *Database, context Context, device DeviceKey, nonce string, replay Error) Error {
|
||||
begun := DeviceKeys_Begin(database, context, nil)
|
||||
if begun.Error != nil {
|
||||
@@ -239,7 +302,7 @@ func DeviceKeys_Register(database *Database, context Context, device DeviceKey,
|
||||
return error
|
||||
}
|
||||
var value_0 string = "\nINSERT INTO server_device_keys(account_id,app_id,device_key_id,client_id,public_key,created_at,last_used_at,revoked_at)\nVALUES(?1,?2,?3,?4,?5,?6,?6,'')\nON CONFLICT(account_id,app_id,device_key_id) DO UPDATE SET\n client_id=excluded.client_id,\n public_key=excluded.public_key,\n last_used_at=excluded.last_used_at,\n revoked_at=''\n"
|
||||
var value_1 zir_9f77619cbb1e2ba7_ExecResult = DeviceKeys_InsertDevice(transaction, context, value_0, device.AccountID, device.AppID, device.KeyID, device.ClientID, device.PublicKey, Timestamp_CanonicalNow())
|
||||
var value_1 zir_0291b470ede4d422_ExecResult = DeviceKeys_InsertDevice(transaction, context, value_0, device.AccountID, device.AppID, device.KeyID, device.ClientID, device.PublicKey, Timestamp_CanonicalNow())
|
||||
inserted := value_1
|
||||
if inserted.Error != nil {
|
||||
return inserted.Error
|
||||
@@ -259,7 +322,7 @@ func DeviceKeys_Revoke(database *Database, context Context, accountID string, re
|
||||
return error
|
||||
}
|
||||
var value_0 string = "\nUPDATE server_device_keys SET revoked_at=?4\nWHERE account_id=?1 AND app_id=?2 AND device_key_id=?3 AND revoked_at=''\n"
|
||||
var value_1 zir_9f77619cbb1e2ba7_ExecResult = DeviceKeys_RevokeDevice(transaction, context, value_0, accountID, request.AppID, request.KeyID, Timestamp_CanonicalNow())
|
||||
var value_1 zir_0291b470ede4d422_ExecResult = DeviceKeys_RevokeDevice(transaction, context, value_0, accountID, request.AppID, request.KeyID, Timestamp_CanonicalNow())
|
||||
revoked := value_1
|
||||
if revoked.Error != nil {
|
||||
return revoked.Error
|
||||
@@ -293,7 +356,7 @@ func DeviceKeys_Active(database *Database, context Context, accountID string, ap
|
||||
|
||||
func DeviceKeys_Touch(database *Database, context Context, accountID string, appID string, keyID string) Error {
|
||||
var value_0 string = "\nUPDATE server_device_keys SET last_used_at=?4\nWHERE account_id=?1 AND app_id=?2 AND device_key_id=?3 AND revoked_at=''\n"
|
||||
var value_1 zir_9f77619cbb1e2ba7_ExecResult = DeviceKeys_TouchDevice(database, context, value_0, accountID, appID, keyID, Timestamp_CanonicalNow())
|
||||
var value_1 zir_0291b470ede4d422_ExecResult = DeviceKeys_TouchDevice(database, context, value_0, accountID, appID, keyID, Timestamp_CanonicalNow())
|
||||
touched := value_1
|
||||
return touched.Error
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@ errors :: #import "errors_go";
|
||||
text :: #import "text_go";
|
||||
timestamp :: #import "timestamp";
|
||||
identity :: #import "identity";
|
||||
accounts :: #import "account_keys";
|
||||
auth :: #import "authentication";
|
||||
codec :: #import "codec";
|
||||
go_sql :: #system_library "go:database/sql";
|
||||
go_strings :: #system_library "go:strings";
|
||||
go_strconv :: #system_library "go:strconv";
|
||||
@@ -146,6 +149,47 @@ ValidRegistration :: (request: DeviceRegistrationRequest) -> bool {
|
||||
}
|
||||
return ValidExpiry(request.ExpiresAt)
|
||||
}
|
||||
VerifyRegistration :: (database: *sql.Database, context: ctx.Context, accountID: string, request: DeviceRegistrationRequest, verifySignature: auth.VerifySignature) -> auth.AuthenticationResult {
|
||||
if !ValidRegistration(request) {
|
||||
return auth.Failure(cast(isize)400, "invalid device registration")
|
||||
}
|
||||
account := accounts.PublicKey(database, context, accountID)
|
||||
if account.error != null {
|
||||
return auth.NativeFailure(account.error)
|
||||
}
|
||||
if !account.found {
|
||||
return auth.Failure(cast(isize)401, "sync account not found")
|
||||
}
|
||||
signature := codec.DecodeBinaryField(request.Signature)
|
||||
if signature.error != "" || signature.value.count != codec.mlDSA44SignatureSize {
|
||||
return auth.Failure(cast(isize)400, "invalid device registration signature")
|
||||
}
|
||||
if !verifySignature(account.value, RegistrationMessage(accountID, request), text.ToBytes(signature.value)) {
|
||||
return auth.Failure(cast(isize)401, "device registration rejected")
|
||||
}
|
||||
return auth.NativeFailure(null)
|
||||
}
|
||||
VerifyRevocation :: (database: *sql.Database, context: ctx.Context, accountID: string, request: DeviceRevocationRequest, verifySignature: auth.VerifySignature) -> auth.AuthenticationResult {
|
||||
if !identity.ValidNamespace(request.AppID) || !identity.ValidClientID(request.KeyID) ||
|
||||
!identity.ValidClientID(request.Nonce) || !ValidExpiry(request.ExpiresAt) {
|
||||
return auth.Failure(cast(isize)400, "invalid device revocation")
|
||||
}
|
||||
account := accounts.PublicKey(database, context, accountID)
|
||||
if account.error != null {
|
||||
return auth.NativeFailure(account.error)
|
||||
}
|
||||
if !account.found {
|
||||
return auth.Failure(cast(isize)401, "sync account not found")
|
||||
}
|
||||
signature := codec.DecodeBinaryField(request.Signature)
|
||||
if signature.error != "" || signature.value.count != codec.mlDSA44SignatureSize {
|
||||
return auth.Failure(cast(isize)400, "invalid device revocation signature")
|
||||
}
|
||||
if !verifySignature(account.value, RevocationMessage(accountID, request), text.ToBytes(signature.value)) {
|
||||
return auth.Failure(cast(isize)401, "device revocation rejected")
|
||||
}
|
||||
return auth.NativeFailure(null)
|
||||
}
|
||||
Register :: (database: *sql.Database, context: ctx.Context, device: DeviceKey, nonce: string, replay: Error) -> Error {
|
||||
begun := Begin(database, context, null)
|
||||
if begun.error != null {
|
||||
|
||||
+25
-4
@@ -52,7 +52,7 @@ field names, Go storage types, order and reflection tags.
|
||||
| `challenge.go` | Ziran | `challenge.zi`: random challenges, expiry, locking, replacement, single-use consumption and base64 preview |
|
||||
| `codec.go` | Ziran | `codec.zi`: exact hexadecimal/base64 decoding and binary encoding |
|
||||
| `config.go` | Ziran | `config.zi`: all fields, environment/file loading, startup settings, strict errors, ephemeral secrets and Ed25519 keys; parsers in `config_values.zi` and `sets.zi` |
|
||||
| `device_keys.go` | Partial Ziran | Records, canonical messages, normalization, validation, atomic registration/revocation, nonce cleanup, lookup/list/touch in `device_keys.zi`; signature verification and HTTP handlers remain in `device_handlers.go` |
|
||||
| `device_keys.go` | Partial Ziran | Records, canonical messages, validation, signature verification, atomic registration/revocation, nonce cleanup and key queries in `device_keys.zi`; HTTP handlers remain in `device_handlers.go` |
|
||||
| `discovery.go` | Go | LAN discovery and runtime cancellation |
|
||||
| `docs.go` | Go | Embedded public API documentation |
|
||||
| `inspect.go` | Go with ported callers | Offline database commands and redaction |
|
||||
@@ -67,9 +67,9 @@ field names, Go storage types, order and reflection tags.
|
||||
| `node_identity.go` | Ziran | `node_identity.zi`: copied native key material, private key-file persistence, pairing records/messages/signatures/validation and namespace claim records/messages/name grammar |
|
||||
| `rate_limit.go` | Ziran | `rate_limit.zi`: concurrent request windows and eviction; `client_address.zi`: native HTTP/IP access, loopback-only proxy trust and address normalization |
|
||||
| `server.go` | Partial Ziran | Identifier/collection grammars in `identity.zi`; HTTP handlers remain Go |
|
||||
| `signed_tx.go` | Partial Ziran | Record, normalization, canonical bytes in `transaction.zi`; decoding, verification and replay remain Go |
|
||||
| `signed_tx.go` | Ziran | `signed_tx.zi`: header decoding, ordered validation, account/device signatures, expiry, replay recording and exact forgetting; record and canonical bytes in `transaction.zi`, JSON serialization in the standard library |
|
||||
| `signing.go` | Ziran | `signing.zi`: canonical account/node/approval bytes and raw-body hashing |
|
||||
| `store.go` | Partial Ziran | Timestamp parsing/normalization in `timestamp.zi`; schema, sync transactions, conflicts and projections remain Go |
|
||||
| `store.go` | Partial Ziran | Timestamp helpers in `timestamp.zi`, public-key lookup in `account_keys.zi`; schema, sync transactions, conflicts and projections remain Go |
|
||||
| `store_timestamps.go` | Ziran | `store_timestamps.zi`: version guard, all 14 columns, canonical rewrites, error wrapping and atomic transaction cleanup |
|
||||
| `sync_ws.go` | Go with ported callers | Authenticated WebSocket framing and connection lifecycle |
|
||||
| `token.go` | Ziran | `token.zi`: bearer-token issue/verify, decimal parsing, exact expiry behavior |
|
||||
@@ -195,7 +195,25 @@ nonce consumption; missing-key revocation returns the native SQL sentinel.
|
||||
Replacement preserves creation time and clears revocation. Listing preserves
|
||||
ordering and nil empty results. Baseline fixtures compare record layouts,
|
||||
messages, lifecycle state, cancellation, commit failures and concurrent replay
|
||||
identity. The original signature checks and HTTP handlers still need porting.
|
||||
identity. Registration/revocation signature checks now also live in Ziran and
|
||||
preserve the original validation order, native account-key query failures and
|
||||
exact signature messages. Their HTTP handlers still need porting.
|
||||
|
||||
`signed_tx.zi` completes signed-header decoding, transaction verification,
|
||||
device signature verification and replay persistence. Header decoding preserves
|
||||
raw JSON and both URL-base64 encodings, Unicode trimming, JSON errors and field
|
||||
normalization. Verification retains protocol/context/ID validation order,
|
||||
decoded request paths, body hashes, expiry limits, account lookup, both signature
|
||||
checks and native errors. Cryptographic verification uses a typed function
|
||||
argument bound to the existing foreign-library verifier. Replay recording
|
||||
retains the original separate expiry cleanup and insertion; a failed device
|
||||
touch leaves the replay recorded, matching the original behavior. Forgetting
|
||||
requires all four identifiers to match and still ignores native SQL errors.
|
||||
Baseline cases compare rejection status/text, callback bytes, database state,
|
||||
malformed headers and simultaneous request verification. `authentication.zi`
|
||||
owns the shared result and signature callback; `authentication_error.go` remains
|
||||
a small conversion to the existing Go HTTP error interface. The HTTP boundary
|
||||
and foreign-library verifier are still part of the unfinished server port.
|
||||
|
||||
## Compiler work exercised by this port
|
||||
|
||||
@@ -250,6 +268,9 @@ preserve record tags, nil/empty slices and pointer destinations. Native key
|
||||
generation preserves public/private/error result order and entropy errors.
|
||||
Native public-key equality and SQL affected-row results preserve Go key types,
|
||||
64-bit counts and error identity in both source and saved IR.
|
||||
Native decoded URL paths and Unix timestamp construction preserve request
|
||||
encoding, signed 64-bit seconds and nanosecond normalization. Typed callbacks
|
||||
carry native byte slices and imported authentication results through saved IR.
|
||||
|
||||
## Next dependencies
|
||||
|
||||
|
||||
@@ -316,7 +316,7 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
if !syncOK {
|
||||
s.metrics.SyncFailures.Add(1)
|
||||
if signedTx != nil {
|
||||
s.store.ForgetSignedTx(r.Context(), *signedTx)
|
||||
SignedTx_Forget(s.store.db, r.Context(), *signedTx)
|
||||
}
|
||||
}
|
||||
}()
|
||||
@@ -363,12 +363,13 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if req.ProtocolVersion >= 6 {
|
||||
tx, err := readSignedTxHeader(r)
|
||||
header := SignedTx_ReadHeader(r)
|
||||
tx, err := header.Value, authenticationError(header.Authentication)
|
||||
if err != nil {
|
||||
s.writeAuthError(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.verifySignedTx(r.Context(), r, body, tx, req.UserIDHash, req.AppID); err != nil {
|
||||
if err := authenticationError(SignedTx_Verify(s.store.db, r.Context(), r, body, tx, req.UserIDHash, req.AppID, s.verifier.Verify, errSignedTxReplay)); err != nil {
|
||||
s.writeAuthError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -1376,7 +1377,8 @@ func (s *Server) handleDeleteAccountWithKey(w http.ResponseWriter, r *http.Reque
|
||||
writeError(w, http.StatusTooManyRequests, "rate limit exceeded")
|
||||
return
|
||||
}
|
||||
publicKey, found, err := s.store.PublicKey(r.Context(), req.UserIDHash)
|
||||
account := AccountKeys_PublicKey(s.store.db, r.Context(), req.UserIDHash)
|
||||
publicKey, found, err := account.Value, account.Found, account.Error
|
||||
if err != nil {
|
||||
slog.Error("load account key", "user", LogSafety_LogText(req.UserIDHash), "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "delete failed")
|
||||
@@ -1419,7 +1421,8 @@ func (s *Server) authenticateSignature(ctx context.Context, userID, publicKeyTex
|
||||
if !ok {
|
||||
return nil, authError{status: http.StatusBadRequest, message: "missing or expired challenge"}
|
||||
}
|
||||
publicKey, found, err := s.store.PublicKey(ctx, userID)
|
||||
account := AccountKeys_PublicKey(s.store.db, ctx, userID)
|
||||
publicKey, found, err := account.Value, account.Found, account.Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1471,7 +1474,8 @@ func (s *Server) authenticateToken(r *http.Request) (string, error) {
|
||||
return "", authError{status: http.StatusUnauthorized, message: "invalid bearer token"}
|
||||
}
|
||||
userID := verified.Value
|
||||
_, found, err := s.store.PublicKey(r.Context(), userID)
|
||||
account := AccountKeys_PublicKey(s.store.db, r.Context(), userID)
|
||||
found, err := account.Found, account.Error
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
+5
-5
@@ -1072,8 +1072,8 @@ func TestSignedAppRegistrationAndProtocolV6Sync(t *testing.T) {
|
||||
}
|
||||
registerBody, err := json.Marshal(SignedAppRegistrationRequest{
|
||||
Manifest: manifest,
|
||||
ManifestSignature: hex.EncodeToString(ed25519.Sign(appPrivate, append([]byte(daochiAppManifestContext+"\n"), manifestBytes...))),
|
||||
ApprovalSignature: hex.EncodeToString(ed25519.Sign(nodePrivate, []byte(Signing_AppApprovalMessage(daochiAppApprovalContext, "testapp", manifestHash)))),
|
||||
ManifestSignature: hex.EncodeToString(ed25519.Sign(appPrivate, append([]byte(AppManifestContext+"\n"), manifestBytes...))),
|
||||
ApprovalSignature: hex.EncodeToString(ed25519.Sign(nodePrivate, []byte(Signing_AppApprovalMessage(AppApprovalContext, "testapp", manifestHash)))),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -3253,8 +3253,8 @@ func TestBearerSyncCanRegisterUserWithPublicKey(t *testing.T) {
|
||||
if payload.Applied.Habits != 1 || len(payload.Changes.Habits) != 1 {
|
||||
t.Fatalf("registered sync response = %#v", payload)
|
||||
}
|
||||
if _, found, err := server.store.PublicKey(t.Context(), userID); err != nil || !found {
|
||||
t.Fatalf("registered public key found=%v err=%v", found, err)
|
||||
if account := AccountKeys_PublicKey(server.store.db, t.Context(), userID); account.Error != nil || !account.Found {
|
||||
t.Fatalf("registered public key found=%v err=%v", account.Found, account.Error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3671,7 +3671,7 @@ func signedTxHeader(t *testing.T, accountID, appID, deviceKeyID, method, path st
|
||||
Signature: hex.EncodeToString(bytes.Repeat([]byte{0x7a}, mlDSA44SignatureSize)),
|
||||
}
|
||||
tx.DeviceSignature = hex.EncodeToString(ed25519.Sign(devicePrivate,
|
||||
[]byte(Transaction_CanonicalMessage(daochiTxContext, tx))))
|
||||
[]byte(Transaction_CanonicalMessage(TransactionContext, tx))))
|
||||
data, err := json.Marshal(tx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
+174
-100
@@ -1,136 +1,210 @@
|
||||
// Code generated by zi2go from signed_tx.zi. DO NOT EDIT.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
sql "database/sql"
|
||||
strings "strings"
|
||||
)
|
||||
|
||||
const (
|
||||
daochiTxContext = "daochi-tx-v1"
|
||||
daochiAppManifestContext = "daochi-app-manifest-v1"
|
||||
daochiAppApprovalContext = "daochi-app-approval-v1"
|
||||
daochiTxMaxFutureSkew = 15 * time.Minute
|
||||
)
|
||||
|
||||
func readSignedTxHeader(r *http.Request) (SignedTxEnvelope, error) {
|
||||
value := strings.TrimSpace(r.Header.Get("X-Daochi-Tx"))
|
||||
if value == "" {
|
||||
return SignedTxEnvelope{}, authError{status: http.StatusUnauthorized, message: "signed transaction required"}
|
||||
}
|
||||
var raw []byte
|
||||
if strings.HasPrefix(value, "{") {
|
||||
raw = []byte(value)
|
||||
} else if decoded, err := base64.RawURLEncoding.DecodeString(value); err == nil {
|
||||
raw = decoded
|
||||
} else if decoded, err := base64.URLEncoding.DecodeString(value); err == nil {
|
||||
raw = decoded
|
||||
} else {
|
||||
return SignedTxEnvelope{}, authError{status: http.StatusBadRequest, message: "invalid signed transaction"}
|
||||
}
|
||||
var tx SignedTxEnvelope
|
||||
if err := json.Unmarshal(raw, &tx); err != nil {
|
||||
return SignedTxEnvelope{}, authError{status: http.StatusBadRequest, message: "invalid signed transaction"}
|
||||
}
|
||||
Transaction_Normalize(&tx)
|
||||
return tx, nil
|
||||
// #import go_types
|
||||
// #import transaction
|
||||
type SignedHeaderResult struct {
|
||||
Value SignedTxEnvelope
|
||||
Authentication AuthenticationResult
|
||||
}
|
||||
|
||||
func (s *Server) verifySignedTx(ctx context.Context, r *http.Request, body []byte, tx SignedTxEnvelope, accountID, appID string) error {
|
||||
type zir_773b400a7b2b4942_ExecResult struct {
|
||||
Value Result
|
||||
Error Error
|
||||
}
|
||||
|
||||
func SignedTx_DeleteExpired(Database *Database, Context Context, Query string, Now int64) zir_773b400a7b2b4942_ExecResult {
|
||||
var result zir_773b400a7b2b4942_ExecResult
|
||||
result.Value, result.Error = (*sql.DB).ExecContext(Database, Context, Query, Now)
|
||||
return result
|
||||
}
|
||||
|
||||
func SignedTx_Insert(Database *Database, Context Context, Query string, AccountID string, TxID string, AppID string, Nonce string, Expiry int64) zir_773b400a7b2b4942_ExecResult {
|
||||
var result zir_773b400a7b2b4942_ExecResult
|
||||
result.Value, result.Error = (*sql.DB).ExecContext(Database, Context, Query, AccountID, TxID, AppID, Nonce, Expiry)
|
||||
return result
|
||||
}
|
||||
|
||||
func SignedTx_Delete(Database *Database, Context Context, Query string, AccountID string, TxID string, AppID string, Nonce string) zir_773b400a7b2b4942_ExecResult {
|
||||
var result zir_773b400a7b2b4942_ExecResult
|
||||
result.Value, result.Error = (*sql.DB).ExecContext(Database, Context, Query, AccountID, TxID, AppID, Nonce)
|
||||
return result
|
||||
}
|
||||
|
||||
const TransactionContext = "daochi-tx-v1"
|
||||
const AppManifestContext = "daochi-app-manifest-v1"
|
||||
const AppApprovalContext = "daochi-app-approval-v1"
|
||||
const MaxFutureSkew = 900000000000
|
||||
|
||||
func SignedTx_ReadHeader(request *Request) SignedHeaderResult {
|
||||
var result SignedHeaderResult = SignedHeaderResult{}
|
||||
value := strings.TrimSpace(HttpGo_HeaderValue(HttpGo_Headers(request), "X-Daochi-Tx"))
|
||||
if value == "" {
|
||||
var value_0 AuthenticationResult = Authentication_Failure(int(401), "signed transaction required")
|
||||
result.Authentication = value_0
|
||||
return result
|
||||
}
|
||||
raw := value
|
||||
var value_1 bool = strings.HasPrefix(value, "{")
|
||||
if !value_1 {
|
||||
decoded := Codec_DecodeBase64(value, true, false)
|
||||
if decoded.Error != "" {
|
||||
decoded = Codec_DecodeBase64(value, true, true)
|
||||
}
|
||||
if decoded.Error != "" {
|
||||
var value_2 AuthenticationResult = Authentication_Failure(int(400), "invalid signed transaction")
|
||||
result.Authentication = value_2
|
||||
return result
|
||||
}
|
||||
raw = decoded.Value
|
||||
}
|
||||
var tx SignedTxEnvelope = SignedTxEnvelope{}
|
||||
var value_3 Error = JsonGo_Unmarshal(TextGo_ToBytes(raw), &(tx))
|
||||
if value_3 != nil {
|
||||
var value_4 AuthenticationResult = Authentication_Failure(int(400), "invalid signed transaction")
|
||||
result.Authentication = value_4
|
||||
return result
|
||||
}
|
||||
Transaction_Normalize(&(tx))
|
||||
result.Value = tx
|
||||
return result
|
||||
}
|
||||
|
||||
func SignedTx_Verify(database *Database, context Context, request *Request, body []uint8, tx SignedTxEnvelope, accountID string, appID string, verifySignature VerifySignature, replay Error) AuthenticationResult {
|
||||
accountID = strings.ToLower(strings.TrimSpace(accountID))
|
||||
appID = strings.TrimSpace(appID)
|
||||
if tx.ProtocolVersion < 6 {
|
||||
return authError{status: http.StatusBadRequest, message: "signed transaction protocol too old"}
|
||||
return Authentication_Failure(int(400), "signed transaction protocol too old")
|
||||
}
|
||||
if tx.SignatureContext != "" && tx.SignatureContext != daochiTxContext {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid signed transaction context"}
|
||||
if tx.SignatureContext != "" && tx.SignatureContext != "daochi-tx-v1" {
|
||||
return Authentication_Failure(int(400), "invalid signed transaction context")
|
||||
}
|
||||
if !Identity_ValidClientID(tx.TxID) || !Identity_ValidClientID(tx.Nonce) {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid signed transaction id"}
|
||||
var value_0 bool = Identity_ValidClientID(tx.TxID)
|
||||
var value_1 bool = !value_0
|
||||
if !value_1 {
|
||||
var value_2 bool = Identity_ValidClientID(tx.Nonce)
|
||||
value_1 = !value_2
|
||||
}
|
||||
if !Identity_ValidUserID(tx.AccountID) || tx.AccountID != accountID {
|
||||
return authError{status: http.StatusUnauthorized, message: "signed transaction account mismatch"}
|
||||
if value_1 {
|
||||
return Authentication_Failure(int(400), "invalid signed transaction id")
|
||||
}
|
||||
if !Identity_ValidNamespace(tx.AppID) || tx.AppID != appID {
|
||||
return authError{status: http.StatusUnauthorized, message: "signed transaction app mismatch"}
|
||||
var value_3 bool = Identity_ValidUserID(tx.AccountID)
|
||||
if !value_3 || tx.AccountID != accountID {
|
||||
return Authentication_Failure(int(401), "signed transaction account mismatch")
|
||||
}
|
||||
if tx.Method != r.Method || tx.Path != r.URL.Path {
|
||||
return authError{status: http.StatusUnauthorized, message: "signed transaction route mismatch"}
|
||||
var value_4 bool = Identity_ValidNamespace(tx.AppID)
|
||||
if !value_4 || tx.AppID != appID {
|
||||
return Authentication_Failure(int(401), "signed transaction app mismatch")
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
if tx.BodySHA256 != hex.EncodeToString(sum[:]) {
|
||||
return authError{status: http.StatusUnauthorized, message: "signed transaction body mismatch"}
|
||||
var value_5 bool = tx.Method != HttpGo_Method(request)
|
||||
var value_6 bool = value_5
|
||||
if !value_6 {
|
||||
var value_7 bool = tx.Path != UrlGo_Path(HttpGo_RequestURL(request))
|
||||
value_6 = value_7
|
||||
}
|
||||
now := time.Now()
|
||||
if tx.ExpiresAt <= now.Unix() || time.Unix(tx.ExpiresAt, 0).After(now.Add(daochiTxMaxFutureSkew)) {
|
||||
return authError{status: http.StatusUnauthorized, message: "signed transaction expired"}
|
||||
if value_6 {
|
||||
return Authentication_Failure(int(401), "signed transaction route mismatch")
|
||||
}
|
||||
publicKey, found, err := s.store.PublicKey(ctx, tx.AccountID)
|
||||
if err != nil {
|
||||
return err
|
||||
if tx.BodySHA256 != Signing_SHA256Hex(body) {
|
||||
return Authentication_Failure(int(401), "signed transaction body mismatch")
|
||||
}
|
||||
if !found {
|
||||
return authError{status: http.StatusUnauthorized, message: "sync account not found"}
|
||||
now := TimeGo_Now()
|
||||
var value_8 bool = tx.ExpiresAt <= TimeGo_Unix(now)
|
||||
var value_9 bool = value_8
|
||||
if !value_9 {
|
||||
var value_10 bool = TimeGo_After(TimeGo_FromUnix(tx.ExpiresAt, 0), TimeGo_Add(now, Duration(900000000000)))
|
||||
value_9 = value_10
|
||||
}
|
||||
signatureField := Codec_DecodeBinaryField(tx.Signature)
|
||||
signature := []byte(signatureField.Value)
|
||||
if signatureField.Error != "" || len(signature) != mlDSA44SignatureSize {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid signed transaction signature"}
|
||||
if value_9 {
|
||||
return Authentication_Failure(int(401), "signed transaction expired")
|
||||
}
|
||||
message := []byte(Transaction_CanonicalMessage(daochiTxContext, tx))
|
||||
if !s.verifier.Verify(publicKey, message, signature) {
|
||||
return authError{status: http.StatusUnauthorized, message: "signed transaction rejected"}
|
||||
account := AccountKeys_PublicKey(database, context, tx.AccountID)
|
||||
if account.Error != nil {
|
||||
return Authentication_NativeFailure(account.Error)
|
||||
}
|
||||
if err := s.verifyDeviceSignedTx(ctx, tx, message); err != nil {
|
||||
return err
|
||||
if !account.Found {
|
||||
return Authentication_Failure(int(401), "sync account not found")
|
||||
}
|
||||
if err := s.store.RecordSignedTx(ctx, tx); err != nil {
|
||||
if errors.Is(err, errSignedTxReplay) {
|
||||
return authError{status: http.StatusConflict, message: "signed transaction replay"}
|
||||
signature := Codec_DecodeBinaryField(tx.Signature)
|
||||
if signature.Error != "" || int64(len(signature.Value)) != 2420 {
|
||||
return Authentication_Failure(int(400), "invalid signed transaction signature")
|
||||
}
|
||||
message := TextGo_ToBytes(Transaction_CanonicalMessage("daochi-tx-v1", tx))
|
||||
var value_11 VerifySignature = verifySignature
|
||||
var value_12 bool = value_11(account.Value, message, TextGo_ToBytes(signature.Value))
|
||||
if !value_12 {
|
||||
return Authentication_Failure(int(401), "signed transaction rejected")
|
||||
}
|
||||
device := SignedTx_VerifyDevice(database, context, tx, message)
|
||||
if device.Status != 0 || device.Error != nil {
|
||||
return device
|
||||
}
|
||||
recorded := SignedTx_Record(database, context, tx, replay)
|
||||
if recorded != nil {
|
||||
if ErrorsGo_Is(recorded, replay) {
|
||||
return Authentication_Failure(int(409), "signed transaction replay")
|
||||
}
|
||||
return err
|
||||
return Authentication_NativeFailure(recorded)
|
||||
}
|
||||
if err := DeviceKeys_Touch(s.store.db, ctx, tx.AccountID, tx.AppID, tx.DeviceKeyID); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
var value_13 AuthenticationResult = Authentication_NativeFailure(DeviceKeys_Touch(database, context, tx.AccountID, tx.AppID, tx.DeviceKeyID))
|
||||
return value_13
|
||||
}
|
||||
|
||||
func (s *Server) verifyDeviceSignedTx(ctx context.Context, tx SignedTxEnvelope, message []byte) error {
|
||||
if !Identity_ValidClientID(tx.DeviceKeyID) {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid device key id"}
|
||||
func SignedTx_VerifyDevice(database *Database, context Context, tx SignedTxEnvelope, message []uint8) AuthenticationResult {
|
||||
var value_0 bool = Identity_ValidClientID(tx.DeviceKeyID)
|
||||
if !value_0 {
|
||||
return Authentication_Failure(int(400), "invalid device key id")
|
||||
}
|
||||
active := DeviceKeys_Active(s.store.db, ctx, tx.AccountID, tx.AppID, tx.DeviceKeyID)
|
||||
deviceKey, found, err := active.Value, active.Found, active.Error
|
||||
if err != nil {
|
||||
return err
|
||||
device := DeviceKeys_Active(database, context, tx.AccountID, tx.AppID, tx.DeviceKeyID)
|
||||
if device.Error != nil {
|
||||
return Authentication_NativeFailure(device.Error)
|
||||
}
|
||||
if !found {
|
||||
return authError{status: http.StatusUnauthorized, message: "device key not registered"}
|
||||
if !device.Found {
|
||||
return Authentication_Failure(int(401), "device key not registered")
|
||||
}
|
||||
publicKeyField := Codec_DecodeBinaryField(deviceKey.PublicKey)
|
||||
publicKey := []byte(publicKeyField.Value)
|
||||
if publicKeyField.Error != "" || len(publicKey) != ed25519.PublicKeySize {
|
||||
return authError{status: http.StatusUnauthorized, message: "invalid app public key"}
|
||||
publicKey := Codec_DecodeBinaryField(device.Value.PublicKey)
|
||||
if publicKey.Error != "" || int64(len(publicKey.Value)) != 32 {
|
||||
return Authentication_Failure(int(401), "invalid app public key")
|
||||
}
|
||||
signatureField := Codec_DecodeBinaryField(tx.DeviceSignature)
|
||||
signature := []byte(signatureField.Value)
|
||||
if signatureField.Error != "" || len(signature) != ed25519.SignatureSize {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid device signature"}
|
||||
signature := Codec_DecodeBinaryField(tx.DeviceSignature)
|
||||
if signature.Error != "" || int64(len(signature.Value)) != 64 {
|
||||
return Authentication_Failure(int(400), "invalid device signature")
|
||||
}
|
||||
if !ed25519.Verify(publicKey, message, signature) {
|
||||
return authError{status: http.StatusUnauthorized, message: "device signature rejected"}
|
||||
var value_1 []uint8 = TextGo_ToBytes(publicKey.Value)
|
||||
var value_2 bool = Ed25519Go_Verify(PublicKey(value_1), message, TextGo_ToBytes(signature.Value))
|
||||
if !value_2 {
|
||||
return Authentication_Failure(int(401), "device signature rejected")
|
||||
}
|
||||
return nil
|
||||
return Authentication_NativeFailure(nil)
|
||||
}
|
||||
|
||||
func canonicalJSON(value any) ([]byte, error) {
|
||||
return json.Marshal(value)
|
||||
func SignedTx_Record(database *Database, context Context, tx SignedTxEnvelope, replay Error) Error {
|
||||
var value_0 zir_773b400a7b2b4942_ExecResult = SignedTx_DeleteExpired(database, context, "DELETE FROM server_signed_transactions WHERE expires_at<?1", int64(TimeGo_Unix(TimeGo_Now())))
|
||||
deleted := value_0
|
||||
if deleted.Error != nil {
|
||||
return deleted.Error
|
||||
}
|
||||
var value_1 string = "INSERT INTO server_signed_transactions(account_id,tx_id,app_id,nonce,expires_at) VALUES(?1,?2,?3,?4,?5)"
|
||||
var value_2 zir_773b400a7b2b4942_ExecResult = SignedTx_Insert(database, context, value_1, tx.AccountID, tx.TxID, tx.AppID, tx.Nonce, int64(tx.ExpiresAt))
|
||||
inserted := value_2
|
||||
var value_3 bool = inserted.Error != nil
|
||||
var value_4 bool = value_3
|
||||
if value_4 {
|
||||
var value_5 bool = strings.Contains(ErrorsGo_Message(inserted.Error), "UNIQUE")
|
||||
value_4 = value_5
|
||||
}
|
||||
if value_4 {
|
||||
return replay
|
||||
}
|
||||
return inserted.Error
|
||||
}
|
||||
|
||||
func SignedTx_Forget(database *Database, context Context, tx SignedTxEnvelope) {
|
||||
var value_0 string = "DELETE FROM server_signed_transactions WHERE account_id=?1 AND tx_id=?2 AND app_id=?3 AND nonce=?4"
|
||||
SignedTx_Delete(database, context, value_0, tx.AccountID, tx.TxID, tx.AppID, tx.Nonce)
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
#import "go_types"
|
||||
#import "transaction"
|
||||
auth :: #import "authentication";
|
||||
accounts :: #import "account_keys";
|
||||
devices :: #import "device_keys";
|
||||
identity :: #import "identity";
|
||||
codec :: #import "codec";
|
||||
signing :: #import "signing";
|
||||
transaction :: #import "transaction";
|
||||
ctx :: #import "context_go";
|
||||
sql :: #import "sql_go";
|
||||
http :: #import "http_go";
|
||||
url :: #import "url_go";
|
||||
text :: #import "text_go";
|
||||
json :: #import "json_go";
|
||||
keys :: #import "ed25519_go";
|
||||
clock :: #import "time_go";
|
||||
errors :: #import "errors_go";
|
||||
go_sql :: #system_library "go:database/sql";
|
||||
go_strings :: #system_library "go:strings";
|
||||
|
||||
TransactionContext :: "daochi-tx-v1";
|
||||
AppManifestContext :: "daochi-app-manifest-v1";
|
||||
AppApprovalContext :: "daochi-app-approval-v1";
|
||||
MaxFutureSkew :: 900000000000;
|
||||
SignedHeaderResult :: struct {
|
||||
value: SignedTxEnvelope
|
||||
authentication: auth.AuthenticationResult
|
||||
}
|
||||
|
||||
#scope_file
|
||||
ExecResult :: struct {
|
||||
value: sql.Result
|
||||
error: Error
|
||||
}
|
||||
TrimSpace :: (value: string) -> string #foreign go_strings;
|
||||
Lower :: (value: string) -> string #foreign go_strings "ToLower";
|
||||
HasPrefix :: (value: string, prefix: string) -> bool #foreign go_strings;
|
||||
Contains :: (value: string, fragment: string) -> bool #foreign go_strings;
|
||||
DeleteExpired :: (database: *sql.Database, context: ctx.Context, query: string, now: s64) -> ExecResult #go_results #foreign go_sql "(*DB).ExecContext";
|
||||
Insert :: (database: *sql.Database, context: ctx.Context, query: string, accountID: string, txID: string, appID: string, nonce: string, expiry: s64) -> ExecResult #go_results #foreign go_sql "(*DB).ExecContext";
|
||||
Delete :: (database: *sql.Database, context: ctx.Context, query: string, accountID: string, txID: string, appID: string, nonce: string) -> ExecResult #go_results #foreign go_sql "(*DB).ExecContext";
|
||||
|
||||
#scope_export
|
||||
ReadHeader :: (request: *http.Request) -> SignedHeaderResult {
|
||||
result: SignedHeaderResult
|
||||
value := TrimSpace(http.HeaderValue(http.Headers(request), "X-Daochi-Tx"))
|
||||
if value == "" {
|
||||
result.authentication = auth.Failure(cast(isize)401, "signed transaction required")
|
||||
return result
|
||||
}
|
||||
raw := value
|
||||
if !HasPrefix(value, "{") {
|
||||
decoded := codec.DecodeBase64(value, true, false)
|
||||
if decoded.error != "" {
|
||||
decoded = codec.DecodeBase64(value, true, true)
|
||||
}
|
||||
if decoded.error != "" {
|
||||
result.authentication = auth.Failure(cast(isize)400, "invalid signed transaction")
|
||||
return result
|
||||
}
|
||||
raw = decoded.value
|
||||
}
|
||||
tx: SignedTxEnvelope
|
||||
if json.Unmarshal(text.ToBytes(raw), *tx) != null {
|
||||
result.authentication = auth.Failure(cast(isize)400, "invalid signed transaction")
|
||||
return result
|
||||
}
|
||||
transaction.Normalize(*tx)
|
||||
result.value = tx
|
||||
return result
|
||||
}
|
||||
|
||||
Verify :: (database: *sql.Database, context: ctx.Context, request: *http.Request, body: []u8, tx: SignedTxEnvelope, accountID: string, appID: string, verifySignature: auth.VerifySignature, replay: Error) -> auth.AuthenticationResult {
|
||||
accountID = Lower(TrimSpace(accountID))
|
||||
appID = TrimSpace(appID)
|
||||
if tx.protocolVersion < 6 {
|
||||
return auth.Failure(cast(isize)400, "signed transaction protocol too old")
|
||||
}
|
||||
if tx.signatureContext != "" && tx.signatureContext != TransactionContext {
|
||||
return auth.Failure(cast(isize)400, "invalid signed transaction context")
|
||||
}
|
||||
if !identity.ValidClientID(tx.txID) || !identity.ValidClientID(tx.nonce) {
|
||||
return auth.Failure(cast(isize)400, "invalid signed transaction id")
|
||||
}
|
||||
if !identity.ValidUserID(tx.accountID) || tx.accountID != accountID {
|
||||
return auth.Failure(cast(isize)401, "signed transaction account mismatch")
|
||||
}
|
||||
if !identity.ValidNamespace(tx.appID) || tx.appID != appID {
|
||||
return auth.Failure(cast(isize)401, "signed transaction app mismatch")
|
||||
}
|
||||
if tx.method != http.Method(request) || tx.path != url.Path(http.RequestURL(request)) {
|
||||
return auth.Failure(cast(isize)401, "signed transaction route mismatch")
|
||||
}
|
||||
if tx.bodySHA256 != signing.SHA256Hex(body) {
|
||||
return auth.Failure(cast(isize)401, "signed transaction body mismatch")
|
||||
}
|
||||
now := clock.Now()
|
||||
if tx.expiresAt <= clock.Unix(now) ||
|
||||
clock.After(clock.FromUnix(tx.expiresAt, 0), clock.Add(now, cast(clock.Duration)MaxFutureSkew)) {
|
||||
return auth.Failure(cast(isize)401, "signed transaction expired")
|
||||
}
|
||||
account := accounts.PublicKey(database, context, tx.accountID)
|
||||
if account.error != null {
|
||||
return auth.NativeFailure(account.error)
|
||||
}
|
||||
if !account.found {
|
||||
return auth.Failure(cast(isize)401, "sync account not found")
|
||||
}
|
||||
signature := codec.DecodeBinaryField(tx.signature)
|
||||
if signature.error != "" || signature.value.count != codec.mlDSA44SignatureSize {
|
||||
return auth.Failure(cast(isize)400, "invalid signed transaction signature")
|
||||
}
|
||||
message := text.ToBytes(transaction.CanonicalMessage(TransactionContext, tx))
|
||||
if !verifySignature(account.value, message, text.ToBytes(signature.value)) {
|
||||
return auth.Failure(cast(isize)401, "signed transaction rejected")
|
||||
}
|
||||
device := VerifyDevice(database, context, tx, message)
|
||||
if device.status != 0 || device.error != null {
|
||||
return device
|
||||
}
|
||||
recorded := Record(database, context, tx, replay)
|
||||
if recorded != null {
|
||||
if errors.Is(recorded, replay) {
|
||||
return auth.Failure(cast(isize)409, "signed transaction replay")
|
||||
}
|
||||
return auth.NativeFailure(recorded)
|
||||
}
|
||||
return auth.NativeFailure(devices.Touch(database, context, tx.accountID, tx.appID, tx.deviceKeyID))
|
||||
}
|
||||
|
||||
VerifyDevice :: (database: *sql.Database, context: ctx.Context, tx: SignedTxEnvelope, message: []u8) -> auth.AuthenticationResult {
|
||||
if !identity.ValidClientID(tx.deviceKeyID) {
|
||||
return auth.Failure(cast(isize)400, "invalid device key id")
|
||||
}
|
||||
device := devices.Active(database, context, tx.accountID, tx.appID, tx.deviceKeyID)
|
||||
if device.error != null {
|
||||
return auth.NativeFailure(device.error)
|
||||
}
|
||||
if !device.found {
|
||||
return auth.Failure(cast(isize)401, "device key not registered")
|
||||
}
|
||||
publicKey := codec.DecodeBinaryField(device.value.PublicKey)
|
||||
if publicKey.error != "" || publicKey.value.count != 32 {
|
||||
return auth.Failure(cast(isize)401, "invalid app public key")
|
||||
}
|
||||
signature := codec.DecodeBinaryField(tx.deviceSignature)
|
||||
if signature.error != "" || signature.value.count != 64 {
|
||||
return auth.Failure(cast(isize)400, "invalid device signature")
|
||||
}
|
||||
if !keys.Verify(cast(keys.PublicKey)text.ToBytes(publicKey.value), message, text.ToBytes(signature.value)) {
|
||||
return auth.Failure(cast(isize)401, "device signature rejected")
|
||||
}
|
||||
return auth.NativeFailure(null)
|
||||
}
|
||||
|
||||
Record :: (database: *sql.Database, context: ctx.Context, tx: SignedTxEnvelope, replay: Error) -> Error {
|
||||
deleted := DeleteExpired(database, context, "DELETE FROM server_signed_transactions WHERE expires_at<?1", clock.Unix(clock.Now()))
|
||||
if deleted.error != null {
|
||||
return deleted.error
|
||||
}
|
||||
inserted := Insert(database, context, "INSERT INTO server_signed_transactions(account_id,tx_id,app_id,nonce,expires_at) VALUES(?1,?2,?3,?4,?5)", tx.accountID, tx.txID, tx.appID, tx.nonce, tx.expiresAt)
|
||||
if inserted.error != null && Contains(errors.Message(inserted.error), "UNIQUE") {
|
||||
return replay
|
||||
}
|
||||
return inserted.error
|
||||
}
|
||||
|
||||
Forget :: (database: *sql.Database, context: ctx.Context, tx: SignedTxEnvelope) {
|
||||
Delete(database, context, "DELETE FROM server_signed_transactions WHERE account_id=?1 AND tx_id=?2 AND app_id=?3 AND nonce=?4", tx.accountID, tx.txID, tx.appID, tx.nonce)
|
||||
}
|
||||
@@ -987,18 +987,6 @@ DROP TABLE server_social_cache;`)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) PublicKey(ctx context.Context, userID string) ([]byte, bool, error) {
|
||||
var key []byte
|
||||
err := s.db.QueryRowContext(ctx, `SELECT public_key FROM server_users WHERE user_id_hash=?1`, userID).Scan(&key)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return key, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) ApplySync(ctx context.Context, req SyncRequest, publicKey []byte) (SyncResult, error) {
|
||||
result, _, err := s.ApplySyncDetailed(ctx, req, publicKey)
|
||||
return result, err
|
||||
|
||||
@@ -46,3 +46,7 @@ func TimeGo_Format(value Time, layout string) string {
|
||||
func TimeGo_Unix(value Time) int64 {
|
||||
return (time.Time).Unix(value)
|
||||
}
|
||||
|
||||
func TimeGo_FromUnix(seconds int64, nanos int64) Time {
|
||||
return time.Unix(int64(seconds), int64(nanos))
|
||||
}
|
||||
+9
-8
@@ -662,7 +662,7 @@ func (s *Server) handleTokenSpend(w http.ResponseWriter, r *http.Request) {
|
||||
signedTx, hasSignedTx, err := s.authorizeTokenApp(r.Context(), r, body, userID, req.AppID, req.AssetID, tokenPermissionSpend)
|
||||
if err != nil {
|
||||
if hasSignedTx {
|
||||
s.store.ForgetSignedTx(r.Context(), signedTx)
|
||||
SignedTx_Forget(s.store.db, r.Context(), signedTx)
|
||||
}
|
||||
s.writeAuthError(w, err)
|
||||
return
|
||||
@@ -670,7 +670,7 @@ func (s *Server) handleTokenSpend(w http.ResponseWriter, r *http.Request) {
|
||||
completed := false
|
||||
defer func() {
|
||||
if hasSignedTx && !completed {
|
||||
s.store.ForgetSignedTx(r.Context(), signedTx)
|
||||
SignedTx_Forget(s.store.db, r.Context(), signedTx)
|
||||
}
|
||||
}()
|
||||
sourceRef := req.Action + ":" + req.IdempotencyKey
|
||||
@@ -733,7 +733,7 @@ func (s *Server) handleGooglePurchaseVerify(w http.ResponseWriter, r *http.Reque
|
||||
signedTx, hasSignedTx, err := s.authorizeTokenApp(r.Context(), r, body, userID, req.AppID, waoziTokenAssetID, tokenPermissionPurchase)
|
||||
if err != nil {
|
||||
if hasSignedTx {
|
||||
s.store.ForgetSignedTx(r.Context(), signedTx)
|
||||
SignedTx_Forget(s.store.db, r.Context(), signedTx)
|
||||
}
|
||||
s.writeAuthError(w, err)
|
||||
return
|
||||
@@ -741,7 +741,7 @@ func (s *Server) handleGooglePurchaseVerify(w http.ResponseWriter, r *http.Reque
|
||||
completed := false
|
||||
defer func() {
|
||||
if hasSignedTx && !completed {
|
||||
s.store.ForgetSignedTx(r.Context(), signedTx)
|
||||
SignedTx_Forget(s.store.db, r.Context(), signedTx)
|
||||
}
|
||||
}()
|
||||
if len(s.cfg.GooglePackageNames) > 0 && !s.cfg.GooglePackageNames[req.PackageName] {
|
||||
@@ -808,7 +808,7 @@ func (s *Server) handleMoneroInvoices(w http.ResponseWriter, r *http.Request) {
|
||||
signedTx, hasSignedTx, err := s.authorizeTokenApp(r.Context(), r, body, userID, req.AppID, waoziTokenAssetID, tokenPermissionPurchase)
|
||||
if err != nil {
|
||||
if hasSignedTx {
|
||||
s.store.ForgetSignedTx(r.Context(), signedTx)
|
||||
SignedTx_Forget(s.store.db, r.Context(), signedTx)
|
||||
}
|
||||
s.writeAuthError(w, err)
|
||||
return
|
||||
@@ -816,7 +816,7 @@ func (s *Server) handleMoneroInvoices(w http.ResponseWriter, r *http.Request) {
|
||||
completed := false
|
||||
defer func() {
|
||||
if hasSignedTx && !completed {
|
||||
s.store.ForgetSignedTx(r.Context(), signedTx)
|
||||
SignedTx_Forget(s.store.db, r.Context(), signedTx)
|
||||
}
|
||||
}()
|
||||
invoice, err := s.store.CreateMoneroInvoice(r.Context(), userID, req.AppID, product, s.cfg)
|
||||
@@ -1188,11 +1188,12 @@ func (s *Server) authorizeTokenApp(ctx context.Context, r *http.Request, body []
|
||||
hasSignedTx := strings.TrimSpace(r.Header.Get("X-Daochi-Tx")) != ""
|
||||
var signedTx SignedTxEnvelope
|
||||
if hasSignedTx {
|
||||
tx, err := readSignedTxHeader(r)
|
||||
header := SignedTx_ReadHeader(r)
|
||||
tx, err := header.Value, authenticationError(header.Authentication)
|
||||
if err != nil {
|
||||
return signedTx, false, err
|
||||
}
|
||||
if err := s.verifySignedTx(ctx, r, body, tx, accountID, appID); err != nil {
|
||||
if err := authenticationError(SignedTx_Verify(s.store.db, ctx, r, body, tx, accountID, appID, s.verifier.Verify, errSignedTxReplay)); err != nil {
|
||||
return signedTx, false, err
|
||||
}
|
||||
signedTx = tx
|
||||
|
||||
+2
-2
@@ -287,11 +287,11 @@ func TestSignedAppManifestReplicatesBeforeOfflineRecords(t *testing.T) {
|
||||
Manifest: manifest,
|
||||
ManifestSignature: encodeHex(ed25519.Sign(
|
||||
appPrivateKey,
|
||||
append([]byte(daochiAppManifestContext+"\n"), manifestBytes...),
|
||||
append([]byte(AppManifestContext+"\n"), manifestBytes...),
|
||||
)),
|
||||
ApprovalSignature: encodeHex(ed25519.Sign(
|
||||
registryPrivateKey,
|
||||
[]byte(Signing_AppApprovalMessage(daochiAppApprovalContext, manifest.AppID, manifestHash)),
|
||||
[]byte(Signing_AppApprovalMessage(AppApprovalContext, manifest.AppID, manifestHash)),
|
||||
)),
|
||||
}
|
||||
if err := sourceStore.UpsertSignedAppManifest(
|
||||
|
||||
@@ -25,6 +25,10 @@ func UrlGo_SchemeRaw(Value *URL) string {
|
||||
return Value.Scheme
|
||||
}
|
||||
|
||||
func UrlGo_PathRaw(Value *URL) string {
|
||||
return Value.Path
|
||||
}
|
||||
|
||||
func UrlGo_Parse(value string) ParseURLResult {
|
||||
return UrlGo_ParseRaw(value)
|
||||
}
|
||||
@@ -37,6 +41,10 @@ func UrlGo_Scheme(value *URL) string {
|
||||
return UrlGo_SchemeRaw(value)
|
||||
}
|
||||
|
||||
func UrlGo_Path(value *URL) string {
|
||||
return UrlGo_PathRaw(value)
|
||||
}
|
||||
|
||||
func UrlGo_EscapedPath(value *URL) string {
|
||||
return (*url.URL).EscapedPath(value)
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -104,7 +105,7 @@ func baselineNormalizeDeviceRevocation(request *DeviceRevocationRequest) {
|
||||
func baselineValidDeviceRequestExpiry(expiresAt int64) bool {
|
||||
now := time.Now()
|
||||
return expiresAt > now.Unix() &&
|
||||
!time.Unix(expiresAt, 0).After(now.Add(daochiTxMaxFutureSkew))
|
||||
!time.Unix(expiresAt, 0).After(now.Add((15 * time.Minute)))
|
||||
}
|
||||
|
||||
func baselineValidDeviceRegistration(request DeviceRegistrationRequest) bool {
|
||||
@@ -171,7 +172,7 @@ WHERE account_id=?1 AND app_id=?2 AND device_key_id=?3 AND revoked_at=''`,
|
||||
|
||||
func baselineRecordDeviceNonce(ctx context.Context, transaction *sql.Tx,
|
||||
accountID, nonce string) error {
|
||||
cutoff := Timestamp_CanonicalTimestamp(time.Now().Add(-2 * daochiTxMaxFutureSkew))
|
||||
cutoff := Timestamp_CanonicalTimestamp(time.Now().Add(-2 * (15 * time.Minute)))
|
||||
if _, err := transaction.ExecContext(ctx, `
|
||||
DELETE FROM server_device_registration_nonces WHERE created_at<?1`, cutoff); err != nil {
|
||||
return err
|
||||
@@ -228,3 +229,49 @@ FROM server_device_keys WHERE account_id=?1 ORDER BY app_id,device_key_id`, acco
|
||||
}
|
||||
return devices, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Server) baselineVerifyDeviceRegistration(ctx context.Context, accountID string, request DeviceRegistrationRequest) error {
|
||||
if !baselineValidDeviceRegistration(request) {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid device registration"}
|
||||
}
|
||||
accountKey, found, err := s.store.baselineAccountPublicKey(ctx, accountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return authError{status: http.StatusUnauthorized, message: "sync account not found"}
|
||||
}
|
||||
signatureField := Codec_DecodeBinaryField(request.Signature)
|
||||
signature := []byte(signatureField.Value)
|
||||
if signatureField.Error != "" || len(signature) != mlDSA44SignatureSize {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid device registration signature"}
|
||||
}
|
||||
message := baselineDeviceRegistrationMessage(accountID, request)
|
||||
if !s.verifier.Verify(accountKey, message, signature) {
|
||||
return authError{status: http.StatusUnauthorized, message: "device registration rejected"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) baselineVerifyDeviceRevocation(ctx context.Context, accountID string, request DeviceRevocationRequest) error {
|
||||
if !Identity_ValidNamespace(request.AppID) || !Identity_ValidClientID(request.KeyID) ||
|
||||
!Identity_ValidClientID(request.Nonce) || !baselineValidDeviceRequestExpiry(request.ExpiresAt) {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid device revocation"}
|
||||
}
|
||||
accountKey, found, err := s.store.baselineAccountPublicKey(ctx, accountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return authError{status: http.StatusUnauthorized, message: "sync account not found"}
|
||||
}
|
||||
signatureField := Codec_DecodeBinaryField(request.Signature)
|
||||
signature := []byte(signatureField.Value)
|
||||
if signatureField.Error != "" || len(signature) != mlDSA44SignatureSize {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid device revocation signature"}
|
||||
}
|
||||
if !s.verifier.Verify(accountKey, baselineDeviceRevocationMessage(accountID, request), signature) {
|
||||
return authError{status: http.StatusUnauthorized, message: "device revocation rejected"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
@@ -117,7 +118,7 @@ type baselinePairingAcceptance struct {
|
||||
func baselinePairingInviteMessage(invite PairingInvite) []byte {
|
||||
addresses := append([]string(nil), invite.Addresses...)
|
||||
sort.Strings(addresses)
|
||||
policy, _ := canonicalJSON(invite.Policy)
|
||||
policy, _ := json.Marshal(invite.Policy)
|
||||
return []byte(fmt.Sprintf("%s\n%d\n%s\n%s\n%s\n%s\n%s\n%s\n%d\n%s\n%s\n",
|
||||
baselinePairingInviteContext, invite.Version, invite.InviteID, invite.NodeID,
|
||||
invite.PublicKey, invite.DisplayName, strings.Join(addresses, ","), invite.SpaceID,
|
||||
@@ -244,7 +245,7 @@ func baselineNormalizeName(name string) string {
|
||||
}
|
||||
|
||||
func baselineNameClaimMessage(claim NameClaim) []byte {
|
||||
services, _ := canonicalJSON(claim.Services)
|
||||
services, _ := json.Marshal(claim.Services)
|
||||
return []byte(fmt.Sprintf("%s\n%d\n%s\n%s\n%s\n%d\n%d\n%s\n",
|
||||
baselineNameClaimContext, claim.Version, claim.SpaceID, claim.Name, claim.NodeID,
|
||||
claim.Sequence, claim.ExpiresAt, Signing_SHA256Hex(services)))
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
baselineTxContext = "daochi-tx-v1"
|
||||
baselineAppManifestContext = "daochi-app-manifest-v1"
|
||||
baselineAppApprovalContext = "daochi-app-approval-v1"
|
||||
baselineTxMaxFutureSkew = 15 * time.Minute
|
||||
)
|
||||
|
||||
func baselineReadSignedTxHeader(r *http.Request) (SignedTxEnvelope, error) {
|
||||
value := strings.TrimSpace(r.Header.Get("X-Daochi-Tx"))
|
||||
if value == "" {
|
||||
return SignedTxEnvelope{}, authError{status: http.StatusUnauthorized, message: "signed transaction required"}
|
||||
}
|
||||
var raw []byte
|
||||
if strings.HasPrefix(value, "{") {
|
||||
raw = []byte(value)
|
||||
} else if decoded, err := base64.RawURLEncoding.DecodeString(value); err == nil {
|
||||
raw = decoded
|
||||
} else if decoded, err := base64.URLEncoding.DecodeString(value); err == nil {
|
||||
raw = decoded
|
||||
} else {
|
||||
return SignedTxEnvelope{}, authError{status: http.StatusBadRequest, message: "invalid signed transaction"}
|
||||
}
|
||||
var tx SignedTxEnvelope
|
||||
if err := json.Unmarshal(raw, &tx); err != nil {
|
||||
return SignedTxEnvelope{}, authError{status: http.StatusBadRequest, message: "invalid signed transaction"}
|
||||
}
|
||||
Transaction_Normalize(&tx)
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
func (s *Server) baselineVerifySignedTx(ctx context.Context, r *http.Request, body []byte, tx SignedTxEnvelope, accountID, appID string) error {
|
||||
accountID = strings.ToLower(strings.TrimSpace(accountID))
|
||||
appID = strings.TrimSpace(appID)
|
||||
if tx.ProtocolVersion < 6 {
|
||||
return authError{status: http.StatusBadRequest, message: "signed transaction protocol too old"}
|
||||
}
|
||||
if tx.SignatureContext != "" && tx.SignatureContext != baselineTxContext {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid signed transaction context"}
|
||||
}
|
||||
if !Identity_ValidClientID(tx.TxID) || !Identity_ValidClientID(tx.Nonce) {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid signed transaction id"}
|
||||
}
|
||||
if !Identity_ValidUserID(tx.AccountID) || tx.AccountID != accountID {
|
||||
return authError{status: http.StatusUnauthorized, message: "signed transaction account mismatch"}
|
||||
}
|
||||
if !Identity_ValidNamespace(tx.AppID) || tx.AppID != appID {
|
||||
return authError{status: http.StatusUnauthorized, message: "signed transaction app mismatch"}
|
||||
}
|
||||
if tx.Method != r.Method || tx.Path != r.URL.Path {
|
||||
return authError{status: http.StatusUnauthorized, message: "signed transaction route mismatch"}
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
if tx.BodySHA256 != hex.EncodeToString(sum[:]) {
|
||||
return authError{status: http.StatusUnauthorized, message: "signed transaction body mismatch"}
|
||||
}
|
||||
now := time.Now()
|
||||
if tx.ExpiresAt <= now.Unix() || time.Unix(tx.ExpiresAt, 0).After(now.Add(baselineTxMaxFutureSkew)) {
|
||||
return authError{status: http.StatusUnauthorized, message: "signed transaction expired"}
|
||||
}
|
||||
publicKey, found, err := s.store.baselineAccountPublicKey(ctx, tx.AccountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return authError{status: http.StatusUnauthorized, message: "sync account not found"}
|
||||
}
|
||||
signatureField := Codec_DecodeBinaryField(tx.Signature)
|
||||
signature := []byte(signatureField.Value)
|
||||
if signatureField.Error != "" || len(signature) != mlDSA44SignatureSize {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid signed transaction signature"}
|
||||
}
|
||||
message := []byte(Transaction_CanonicalMessage(baselineTxContext, tx))
|
||||
if !s.verifier.Verify(publicKey, message, signature) {
|
||||
return authError{status: http.StatusUnauthorized, message: "signed transaction rejected"}
|
||||
}
|
||||
if err := s.baselineVerifyDeviceSignedTx(ctx, tx, message); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.store.baselineRecordSignedTx(ctx, tx); err != nil {
|
||||
if errors.Is(err, errSignedTxReplay) {
|
||||
return authError{status: http.StatusConflict, message: "signed transaction replay"}
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := s.store.baselineTouchDeviceKey(ctx, tx.AccountID, tx.AppID, tx.DeviceKeyID); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) baselineVerifyDeviceSignedTx(ctx context.Context, tx SignedTxEnvelope, message []byte) error {
|
||||
if !Identity_ValidClientID(tx.DeviceKeyID) {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid device key id"}
|
||||
}
|
||||
deviceKey, found, err := s.store.baselineActiveDeviceKey(ctx, tx.AccountID, tx.AppID, tx.DeviceKeyID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return authError{status: http.StatusUnauthorized, message: "device key not registered"}
|
||||
}
|
||||
publicKeyField := Codec_DecodeBinaryField(deviceKey.PublicKey)
|
||||
publicKey := []byte(publicKeyField.Value)
|
||||
if publicKeyField.Error != "" || len(publicKey) != ed25519.PublicKeySize {
|
||||
return authError{status: http.StatusUnauthorized, message: "invalid app public key"}
|
||||
}
|
||||
signatureField := Codec_DecodeBinaryField(tx.DeviceSignature)
|
||||
signature := []byte(signatureField.Value)
|
||||
if signatureField.Error != "" || len(signature) != ed25519.SignatureSize {
|
||||
return authError{status: http.StatusBadRequest, message: "invalid device signature"}
|
||||
}
|
||||
if !ed25519.Verify(publicKey, message, signature) {
|
||||
return authError{status: http.StatusUnauthorized, message: "device signature rejected"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) baselineRecordSignedTx(ctx context.Context, tx SignedTxEnvelope) error {
|
||||
if _, err := s.db.ExecContext(ctx, `DELETE FROM server_signed_transactions WHERE expires_at<?1`, time.Now().Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO server_signed_transactions(account_id,tx_id,app_id,nonce,expires_at)
|
||||
VALUES(?1,?2,?3,?4,?5)`, tx.AccountID, tx.TxID, tx.AppID, tx.Nonce, tx.ExpiresAt)
|
||||
if err != nil && strings.Contains(err.Error(), "UNIQUE") {
|
||||
return errSignedTxReplay
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) baselineForgetSignedTx(ctx context.Context, tx SignedTxEnvelope) {
|
||||
_, _ = s.db.ExecContext(ctx, `
|
||||
DELETE FROM server_signed_transactions
|
||||
WHERE account_id=?1 AND tx_id=?2 AND app_id=?3 AND nonce=?4`,
|
||||
tx.AccountID, tx.TxID, tx.AppID, tx.Nonce)
|
||||
}
|
||||
|
||||
func (s *Store) baselineAccountPublicKey(ctx context.Context, userID string) ([]byte, bool, error) {
|
||||
var key []byte
|
||||
err := s.db.QueryRowContext(ctx, `SELECT public_key FROM server_users WHERE user_id_hash=?1`, userID).Scan(&key)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return key, true, nil
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type signatureObservation struct {
|
||||
key []byte
|
||||
message []byte
|
||||
signature []byte
|
||||
}
|
||||
|
||||
type transactionVerifier struct {
|
||||
accept bool
|
||||
calls []signatureObservation
|
||||
}
|
||||
|
||||
func (verifier *transactionVerifier) Verify(key, message, signature []byte) bool {
|
||||
verifier.calls = append(verifier.calls, signatureObservation{
|
||||
key: append([]byte(nil), key...), message: append([]byte(nil), message...),
|
||||
signature: append([]byte(nil), signature...),
|
||||
})
|
||||
return verifier.accept
|
||||
}
|
||||
|
||||
func equalAuthenticationError(actual, expected error) bool {
|
||||
var got, want authError
|
||||
gotAuth, wantAuth := errors.As(actual, &got), errors.As(expected, &want)
|
||||
if gotAuth || wantAuth {
|
||||
return gotAuth && wantAuth && got == want
|
||||
}
|
||||
return sameIdentityError(actual, expected)
|
||||
}
|
||||
|
||||
func TestZiranSignedTransactionHeaderAgainstBaseline(t *testing.T) {
|
||||
values := []string{"", "\u2003\t", "!", "{", "{}", `{"tx_id":42}`, `{"expires_at":9223372036854775808}`,
|
||||
`{"tx_id":" first ","tx_id":" second ","account_id":" AA ","method":" post "}`,
|
||||
"{\"path\":\"\xff\"}", "{} null"}
|
||||
for _, raw := range []string{"null", "{}", "[]", `{"tx_id":" id ","nonce":" nonce ","signature":" sig "}`, "{bad", "{} true"} {
|
||||
values = append(values, base64.RawURLEncoding.EncodeToString([]byte(raw)), base64.URLEncoding.EncodeToString([]byte(raw)))
|
||||
}
|
||||
random := rand.New(rand.NewSource(42))
|
||||
for index := 0; index < 500; index++ {
|
||||
data := make([]byte, random.Intn(128))
|
||||
_, _ = random.Read(data)
|
||||
values = append(values, string(data), base64.RawURLEncoding.EncodeToString(data))
|
||||
}
|
||||
for _, value := range values {
|
||||
request := httptest.NewRequest(http.MethodPost, "/signed", nil)
|
||||
request.Header.Set("X-Daochi-Tx", value)
|
||||
got := SignedTx_ReadHeader(request)
|
||||
want, err := baselineReadSignedTxHeader(request)
|
||||
if !reflect.DeepEqual(got.Value, want) || !equalAuthenticationError(authenticationError(got.Authentication), err) {
|
||||
t.Fatalf("header %q = %#v, baseline = %#v, %v", value, got, want, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func signedTransactionFixture(t *testing.T) (*Store, *http.Request, SignedTxEnvelope, ed25519.PrivateKey, []byte) {
|
||||
t.Helper()
|
||||
store := deviceStoreFixture(t)
|
||||
accountID := strings.Repeat("a", 64)
|
||||
key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x42}, ed25519.SeedSize))
|
||||
_, err := store.db.Exec(`
|
||||
ALTER TABLE server_users ADD COLUMN public_key BLOB;
|
||||
CREATE TABLE server_signed_transactions (
|
||||
account_id TEXT NOT NULL, tx_id TEXT NOT NULL, app_id TEXT NOT NULL,
|
||||
nonce TEXT NOT NULL, expires_at INTEGER NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY(account_id,tx_id), UNIQUE(account_id,app_id,nonce)
|
||||
);`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.db.Exec("UPDATE server_users SET user_id_hash=?1,public_key=?2", accountID, []byte{0, 1, 255}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
device := DeviceKey{AccountID: accountID, AppID: "inbe", KeyID: "device-key", ClientID: "client-test",
|
||||
PublicKey: hex.EncodeToString(key.Public().(ed25519.PublicKey))}
|
||||
if err := store.baselineRegisterDeviceKey(t.Context(), device, "registered"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := []byte("\x00\xff日本語")
|
||||
request := httptest.NewRequest(http.MethodPost, "http://home.example/a%2Fb", nil)
|
||||
tx := SignedTxEnvelope{ProtocolVersion: 6, TxID: "transaction", AccountID: accountID, AppID: "inbe",
|
||||
DeviceKeyID: "device-key", Method: request.Method, Path: request.URL.Path, BodySHA256: Signing_SHA256Hex(body),
|
||||
Nonce: "nonce-test", ExpiresAt: time.Now().Add(time.Minute).Unix(), SignatureContext: baselineTxContext,
|
||||
Signature: hex.EncodeToString(bytes.Repeat([]byte{0x33}, mlDSA44SignatureSize))}
|
||||
signDeviceTransaction(&tx, key)
|
||||
return store, request, tx, key, body
|
||||
}
|
||||
|
||||
func signDeviceTransaction(tx *SignedTxEnvelope, key ed25519.PrivateKey) {
|
||||
tx.DeviceSignature = hex.EncodeToString(ed25519.Sign(key, []byte(Transaction_CanonicalMessage(baselineTxContext, *tx))))
|
||||
}
|
||||
|
||||
func signedTransactionRows(t *testing.T, store *Store) []SignedTxEnvelope {
|
||||
t.Helper()
|
||||
rows, err := store.db.Query("SELECT account_id,tx_id,app_id,nonce,expires_at FROM server_signed_transactions ORDER BY account_id,tx_id")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var result []SignedTxEnvelope
|
||||
for rows.Next() {
|
||||
var tx SignedTxEnvelope
|
||||
if err := rows.Scan(&tx.AccountID, &tx.TxID, &tx.AppID, &tx.Nonce, &tx.ExpiresAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result = append(result, tx)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func TestZiranSignedTransactionVerificationAgainstBaseline(t *testing.T) {
|
||||
failures := map[string]authError{
|
||||
"old protocol": {400, "signed transaction protocol too old"},
|
||||
"wrong context": {400, "invalid signed transaction context"},
|
||||
"bad ID": {400, "invalid signed transaction id"},
|
||||
"account mismatch": {401, "signed transaction account mismatch"},
|
||||
"app mismatch": {401, "signed transaction app mismatch"},
|
||||
"method": {401, "signed transaction route mismatch"},
|
||||
"escaped path": {401, "signed transaction route mismatch"},
|
||||
"body": {401, "signed transaction body mismatch"},
|
||||
"expired": {401, "signed transaction expired"},
|
||||
"future": {401, "signed transaction expired"},
|
||||
"missing account": {401, "sync account not found"},
|
||||
"short signature": {400, "invalid signed transaction signature"},
|
||||
"rejected account": {401, "signed transaction rejected"},
|
||||
"bad device ID": {400, "invalid device key id"},
|
||||
"missing device": {401, "device key not registered"},
|
||||
"revoked device": {401, "device key not registered"},
|
||||
"bad device key": {401, "invalid app public key"},
|
||||
"short device signature": {400, "invalid device signature"},
|
||||
"wrong device signature": {401, "device signature rejected"},
|
||||
"replay": {409, "signed transaction replay"},
|
||||
}
|
||||
for _, mode := range []string{"valid", "old protocol", "wrong context", "bad ID", "account mismatch", "app mismatch", "method", "escaped path", "body", "expired", "future", "missing account", "short signature", "rejected account", "bad device ID", "missing device", "revoked device", "bad device key", "short device signature", "wrong device signature", "replay", "cleanup error", "insert error", "touch error", "canceled"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
actual, request, tx, key, body := signedTransactionFixture(t)
|
||||
expected, _, _, _, _ := signedTransactionFixture(t)
|
||||
gotVerifier, wantVerifier := &transactionVerifier{accept: true}, &transactionVerifier{accept: true}
|
||||
query := ""
|
||||
switch mode {
|
||||
case "old protocol":
|
||||
tx.ProtocolVersion = 5
|
||||
tx.TxID = "!"
|
||||
case "wrong context":
|
||||
tx.SignatureContext = "untrusted"
|
||||
case "bad ID":
|
||||
tx.Nonce = "!"
|
||||
case "account mismatch":
|
||||
tx.AccountID = strings.Repeat("b", 64)
|
||||
case "app mismatch":
|
||||
tx.AppID = "other"
|
||||
case "method":
|
||||
tx.Method = "post"
|
||||
case "escaped path":
|
||||
tx.Path = request.URL.EscapedPath()
|
||||
case "body":
|
||||
tx.BodySHA256 = strings.Repeat("0", 64)
|
||||
case "expired":
|
||||
tx.ExpiresAt = 0
|
||||
case "future":
|
||||
tx.ExpiresAt = time.Now().Add(time.Hour).Unix()
|
||||
case "missing account":
|
||||
query = "DELETE FROM server_users"
|
||||
case "short signature":
|
||||
tx.Signature = "00"
|
||||
case "rejected account":
|
||||
gotVerifier.accept, wantVerifier.accept = false, false
|
||||
case "bad device ID":
|
||||
tx.DeviceKeyID = "!"
|
||||
case "missing device":
|
||||
query = "DELETE FROM server_device_keys"
|
||||
case "revoked device":
|
||||
query = "UPDATE server_device_keys SET revoked_at='revoked'"
|
||||
case "bad device key":
|
||||
query = "UPDATE server_device_keys SET public_key='!'"
|
||||
case "replay":
|
||||
for _, store := range []*Store{actual, expected} {
|
||||
if err := store.baselineRecordSignedTx(t.Context(), tx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
case "cleanup error":
|
||||
query = "DROP TABLE server_signed_transactions"
|
||||
case "insert error":
|
||||
query = "CREATE TRIGGER reject_tx BEFORE INSERT ON server_signed_transactions BEGIN SELECT RAISE(ABORT,'insert rejected'); END"
|
||||
case "touch error":
|
||||
query = "CREATE TRIGGER reject_touch BEFORE UPDATE ON server_device_keys BEGIN SELECT RAISE(ABORT,'touch rejected'); END"
|
||||
}
|
||||
signDeviceTransaction(&tx, key)
|
||||
if mode == "short device signature" {
|
||||
tx.DeviceSignature = "00"
|
||||
}
|
||||
if mode == "wrong device signature" {
|
||||
tx.DeviceSignature = hex.EncodeToString(bytes.Repeat([]byte{0x11}, ed25519.SignatureSize))
|
||||
}
|
||||
if query != "" {
|
||||
for _, store := range []*Store{actual, expected} {
|
||||
if _, err := store.db.Exec(query); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx := t.Context()
|
||||
if mode == "canceled" {
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
ctx = canceled
|
||||
}
|
||||
accountID := "\u2003" + strings.ToUpper(strings.Repeat("a", 64)) + "\t"
|
||||
got := authenticationError(SignedTx_Verify(actual.db, ctx, request, body, tx, accountID, " inbe ", gotVerifier.Verify, errSignedTxReplay))
|
||||
server := &Server{store: expected, verifier: wantVerifier}
|
||||
want := server.baselineVerifySignedTx(ctx, request, body, tx, accountID, " inbe ")
|
||||
if !equalAuthenticationError(got, want) || !reflect.DeepEqual(gotVerifier.calls, wantVerifier.calls) {
|
||||
t.Fatalf("verification = %v, baseline = %v; calls = %#v, baseline = %#v", got, want, gotVerifier.calls, wantVerifier.calls)
|
||||
}
|
||||
if mode == "valid" && got != nil {
|
||||
t.Fatal("valid transaction rejected", got)
|
||||
}
|
||||
if failure, ok := failures[mode]; ok && !equalAuthenticationError(got, failure) {
|
||||
t.Fatalf("validation reached the wrong failure: %v, want %v", got, failure)
|
||||
}
|
||||
if mode == "canceled" && got != context.Canceled {
|
||||
t.Fatal("cancellation error lost identity", got)
|
||||
}
|
||||
if mode != "cleanup error" && !reflect.DeepEqual(signedTransactionRows(t, actual), signedTransactionRows(t, expected)) {
|
||||
t.Fatal("verification changed replay persistence")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestZiranSignedTransactionConcurrentVerificationIsSingleUse(t *testing.T) {
|
||||
store, request, tx, _, body := signedTransactionFixture(t)
|
||||
verify := func(key, message, signature []byte) bool {
|
||||
return bytes.Equal(key, []byte{0, 1, 255}) &&
|
||||
bytes.Equal(message, []byte(Transaction_CanonicalMessage(baselineTxContext, tx))) &&
|
||||
len(signature) == mlDSA44SignatureSize
|
||||
}
|
||||
results := make(chan AuthenticationResult, 16)
|
||||
var workers sync.WaitGroup
|
||||
for index := 0; index < cap(results); index++ {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
results <- SignedTx_Verify(store.db, context.Background(), request, body, tx, tx.AccountID, tx.AppID, verify, errSignedTxReplay)
|
||||
}()
|
||||
}
|
||||
workers.Wait()
|
||||
close(results)
|
||||
accepted := 0
|
||||
for result := range results {
|
||||
if err := authenticationError(result); err == nil {
|
||||
accepted++
|
||||
} else if !equalAuthenticationError(err, authError{409, "signed transaction replay"}) {
|
||||
t.Fatalf("concurrent verification = %v", err)
|
||||
}
|
||||
}
|
||||
if accepted != 1 {
|
||||
t.Fatalf("signed transaction verified %d times", accepted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestZiranSignedTransactionRecordAndForgetAgainstBaseline(t *testing.T) {
|
||||
actual, _, tx, _, _ := signedTransactionFixture(t)
|
||||
expected, _, _, _, _ := signedTransactionFixture(t)
|
||||
for _, item := range []SignedTxEnvelope{tx, tx, {AccountID: tx.AccountID, AppID: tx.AppID, TxID: "other", Nonce: tx.Nonce, ExpiresAt: tx.ExpiresAt}} {
|
||||
got := SignedTx_Record(actual.db, t.Context(), item, errSignedTxReplay)
|
||||
want := expected.baselineRecordSignedTx(t.Context(), item)
|
||||
if got != want && !sameIdentityError(got, want) {
|
||||
t.Fatalf("replay recording = %v, baseline = %v", got, want)
|
||||
}
|
||||
if !reflect.DeepEqual(signedTransactionRows(t, actual), signedTransactionRows(t, expected)) {
|
||||
t.Fatal("recorded replay state differs")
|
||||
}
|
||||
}
|
||||
wrong := tx
|
||||
wrong.Nonce = "different"
|
||||
for _, item := range []SignedTxEnvelope{wrong, tx, tx} {
|
||||
SignedTx_Forget(actual.db, t.Context(), item)
|
||||
expected.baselineForgetSignedTx(t.Context(), item)
|
||||
if !reflect.DeepEqual(signedTransactionRows(t, actual), signedTransactionRows(t, expected)) {
|
||||
t.Fatal("forget removed a mismatched transaction")
|
||||
}
|
||||
}
|
||||
const consumers = 16
|
||||
var workers sync.WaitGroup
|
||||
results := make(chan error, consumers)
|
||||
for index := 0; index < consumers; index++ {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
results <- SignedTx_Record(actual.db, context.Background(), tx, errSignedTxReplay)
|
||||
}()
|
||||
}
|
||||
workers.Wait()
|
||||
close(results)
|
||||
accepted := 0
|
||||
for err := range results {
|
||||
if err == nil {
|
||||
accepted++
|
||||
} else if err != errSignedTxReplay {
|
||||
t.Fatal("concurrent replay lost sentinel identity", err)
|
||||
}
|
||||
}
|
||||
if accepted != 1 {
|
||||
t.Fatalf("transaction accepted %d times", accepted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestZiranAccountPublicKeyPreservesNativeSQLResults(t *testing.T) {
|
||||
actual, _, tx, _, _ := signedTransactionFixture(t)
|
||||
for _, query := range []string{"", "UPDATE server_users SET public_key=x''", "DELETE FROM server_users", "DROP TABLE server_users"} {
|
||||
if query != "" {
|
||||
if _, err := actual.db.Exec(query); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got := AccountKeys_PublicKey(actual.db, t.Context(), tx.AccountID)
|
||||
want, found, err := actual.baselineAccountPublicKey(t.Context(), tx.AccountID)
|
||||
if !reflect.DeepEqual(got.Value, want) || got.Found != found || !sameIdentityError(got.Error, err) {
|
||||
t.Fatalf("account key = %#v, baseline = %v, %v, %v", got, want, found, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestZiranSignedHeaderJSONKeepsReleasedTags(t *testing.T) {
|
||||
_, request, tx, _, _ := signedTransactionFixture(t)
|
||||
raw, err := json.Marshal(tx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request.Header.Set("X-Daochi-Tx", string(raw))
|
||||
got := SignedTx_ReadHeader(request)
|
||||
if err := authenticationError(got.Authentication); err != nil || !reflect.DeepEqual(got.Value, tx) {
|
||||
t.Fatalf("signed header JSON = %#v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestZiranDeviceSignatureValidationAgainstBaseline(t *testing.T) {
|
||||
for _, mode := range []string{"valid", "bad app", "short key ID", "expired", "future", "malformed signature", "short signature", "missing account", "account error", "rejected", "canceled"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
actual, _, tx, key, _ := signedTransactionFixture(t)
|
||||
expected, _, _, _, _ := signedTransactionFixture(t)
|
||||
registration := DeviceRegistrationRequest{
|
||||
AppID: tx.AppID, KeyID: tx.DeviceKeyID, ClientID: "client-test",
|
||||
PublicKey: hex.EncodeToString(key.Public().(ed25519.PublicKey)),
|
||||
Nonce: "registration-nonce", ExpiresAt: tx.ExpiresAt, Signature: tx.Signature,
|
||||
}
|
||||
query := ""
|
||||
gotVerifier, wantVerifier := &transactionVerifier{accept: true}, &transactionVerifier{accept: true}
|
||||
switch mode {
|
||||
case "bad app":
|
||||
registration.AppID = "!"
|
||||
case "short key ID":
|
||||
registration.KeyID = "short"
|
||||
case "expired":
|
||||
registration.ExpiresAt = 0
|
||||
case "future":
|
||||
registration.ExpiresAt = time.Now().Add(time.Hour).Unix()
|
||||
case "malformed signature":
|
||||
registration.Signature = "!"
|
||||
case "short signature":
|
||||
registration.Signature = "00"
|
||||
case "missing account":
|
||||
query = "DELETE FROM server_users"
|
||||
case "account error":
|
||||
query = "DROP TABLE server_users"
|
||||
case "rejected":
|
||||
gotVerifier.accept, wantVerifier.accept = false, false
|
||||
}
|
||||
if query != "" {
|
||||
for _, store := range []*Store{actual, expected} {
|
||||
if _, err := store.db.Exec(query); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx := t.Context()
|
||||
if mode == "canceled" {
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
ctx = canceled
|
||||
}
|
||||
server := &Server{store: expected, verifier: wantVerifier}
|
||||
got := authenticationError(DeviceKeys_VerifyRegistration(actual.db, ctx, tx.AccountID, registration, gotVerifier.Verify))
|
||||
want := server.baselineVerifyDeviceRegistration(ctx, tx.AccountID, registration)
|
||||
if !equalAuthenticationError(got, want) || !reflect.DeepEqual(gotVerifier.calls, wantVerifier.calls) {
|
||||
t.Fatalf("registration verification = %v, baseline = %v; signature arguments differ = %v", got, want, !reflect.DeepEqual(gotVerifier.calls, wantVerifier.calls))
|
||||
}
|
||||
if mode == "valid" && (got != nil || len(gotVerifier.calls) != 1) {
|
||||
t.Fatal("valid registration did not verify its signature", got)
|
||||
}
|
||||
gotVerifier.calls, wantVerifier.calls = nil, nil
|
||||
revocation := DeviceRevocationRequest{AppID: registration.AppID, KeyID: registration.KeyID,
|
||||
Nonce: registration.Nonce, ExpiresAt: registration.ExpiresAt, Signature: registration.Signature}
|
||||
got = authenticationError(DeviceKeys_VerifyRevocation(actual.db, ctx, tx.AccountID, revocation, gotVerifier.Verify))
|
||||
want = server.baselineVerifyDeviceRevocation(ctx, tx.AccountID, revocation)
|
||||
if !equalAuthenticationError(got, want) || !reflect.DeepEqual(gotVerifier.calls, wantVerifier.calls) {
|
||||
t.Fatalf("revocation verification = %v, baseline = %v; signature arguments differ = %v", got, want, !reflect.DeepEqual(gotVerifier.calls, wantVerifier.calls))
|
||||
}
|
||||
if mode == "valid" && (got != nil || len(gotVerifier.calls) != 1) {
|
||||
t.Fatal("valid revocation did not verify its signature", got)
|
||||
}
|
||||
if mode == "canceled" && got != context.Canceled {
|
||||
t.Fatal("revocation cancellation lost identity", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user