diff --git a/account_keys.go b/account_keys.go new file mode 100644 index 0000000..6777b4d --- /dev/null +++ b/account_keys.go @@ -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 +} diff --git a/account_keys.zi b/account_keys.zi new file mode 100644 index 0000000..ca9f02f --- /dev/null +++ b/account_keys.zi @@ -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 +} diff --git a/app_manifest.go b/app_manifest.go index ca37f51..58cef77 100644 --- a/app_manifest.go +++ b/app_manifest.go @@ -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 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 +} diff --git a/authentication_error.go b/authentication_error.go new file mode 100644 index 0000000..8defaa1 --- /dev/null +++ b/authentication_error.go @@ -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 +} diff --git a/device_handlers.go b/device_handlers.go index 77fbd50..7ca8fa5 100644 --- a/device_handlers.go +++ b/device_handlers.go @@ -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 } diff --git a/device_keys.go b/device_keys.go index 0d6771a..4924052 100644 --- a/device_keys.go +++ b/device_keys.go @@ -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 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 { diff --git a/docs/ziran-port.md b/docs/ziran-port.md index c4644b7..a7e0796 100644 --- a/docs/ziran-port.md +++ b/docs/ziran-port.md @@ -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 diff --git a/server.go b/server.go index 1c7d39d..0cc869a 100644 --- a/server.go +++ b/server.go @@ -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 } diff --git a/server_test.go b/server_test.go index 90d79f3..329f189 100644 --- a/server_test.go +++ b/server_test.go @@ -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) diff --git a/signed_tx.go b/signed_tx.go index b67b1c4..f9eafbb 100644 --- a/signed_tx.go +++ b/signed_tx.go @@ -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 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 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 diff --git a/trust_test.go b/trust_test.go index a28f4cb..a623e25 100644 --- a/trust_test.go +++ b/trust_test.go @@ -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( diff --git a/url_go.go b/url_go.go index df56924..4a4e012 100644 --- a/url_go.go +++ b/url_go.go @@ -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) } diff --git a/ziran_device_keys_baseline_test.go b/ziran_device_keys_baseline_test.go index 3f5be56..1db3177 100644 --- a/ziran_device_keys_baseline_test.go +++ b/ziran_device_keys_baseline_test.go @@ -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