|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | +"""StandardKeyMetadata Avro serialization. |
| 18 | +
|
| 19 | +Wire format: ``0x01 version byte || Avro-encoded fields`` |
| 20 | +
|
| 21 | +Avro schema: |
| 22 | + - encryption_key: bytes (required) |
| 23 | + - aad_prefix: union[null, bytes] (optional) |
| 24 | + - file_length: union[null, long] (optional) |
| 25 | +""" |
| 26 | + |
| 27 | +from __future__ import annotations |
| 28 | + |
| 29 | +from dataclasses import dataclass |
| 30 | + |
| 31 | +V1 = 0x01 |
| 32 | + |
| 33 | + |
| 34 | +def _read_avro_long(data: bytes, offset: int) -> tuple[int, int]: |
| 35 | + """Read a zigzag-encoded Avro long from data at offset. Returns (value, new_offset).""" |
| 36 | + result = 0 |
| 37 | + shift = 0 |
| 38 | + while True: |
| 39 | + if offset >= len(data): |
| 40 | + raise ValueError("Unexpected end of Avro data reading long") |
| 41 | + b = data[offset] |
| 42 | + offset += 1 |
| 43 | + result |= (b & 0x7F) << shift |
| 44 | + if (b & 0x80) == 0: |
| 45 | + break |
| 46 | + shift += 7 |
| 47 | + # Zigzag decode |
| 48 | + return (result >> 1) ^ -(result & 1), offset |
| 49 | + |
| 50 | + |
| 51 | +def _read_avro_bytes(data: bytes, offset: int) -> tuple[bytes, int]: |
| 52 | + """Read Avro bytes (length-prefixed). Returns (bytes_value, new_offset).""" |
| 53 | + length, offset = _read_avro_long(data, offset) |
| 54 | + if length < 0: |
| 55 | + raise ValueError(f"Negative Avro bytes length: {length}") |
| 56 | + end = offset + length |
| 57 | + if end > len(data): |
| 58 | + raise ValueError("Unexpected end of Avro data reading bytes") |
| 59 | + return data[offset:end], end |
| 60 | + |
| 61 | + |
| 62 | +@dataclass(frozen=True) |
| 63 | +class StandardKeyMetadata: |
| 64 | + """Standard key metadata for Iceberg table encryption. |
| 65 | +
|
| 66 | + Contains the plaintext encryption key (DEK), AAD prefix, and optional file length. |
| 67 | + """ |
| 68 | + |
| 69 | + encryption_key: bytes |
| 70 | + aad_prefix: bytes = b"" |
| 71 | + file_length: int | None = None |
| 72 | + |
| 73 | + @staticmethod |
| 74 | + def deserialize(data: bytes) -> StandardKeyMetadata: |
| 75 | + """Deserialize from wire format: ``0x01 version || Avro-encoded fields``.""" |
| 76 | + if not data: |
| 77 | + raise ValueError("Empty key metadata buffer") |
| 78 | + |
| 79 | + version = data[0] |
| 80 | + if version != V1: |
| 81 | + raise ValueError(f"Unsupported key metadata version: {version}") |
| 82 | + |
| 83 | + offset = 1 |
| 84 | + |
| 85 | + # Read encryption_key (required bytes) |
| 86 | + encryption_key, offset = _read_avro_bytes(data, offset) |
| 87 | + |
| 88 | + # Read aad_prefix (optional: union[null, bytes]) |
| 89 | + union_index, offset = _read_avro_long(data, offset) |
| 90 | + if union_index == 0: |
| 91 | + aad_prefix = b"" |
| 92 | + elif union_index == 1: |
| 93 | + aad_prefix, offset = _read_avro_bytes(data, offset) |
| 94 | + else: |
| 95 | + raise ValueError(f"Invalid union index for aad_prefix: {union_index}") |
| 96 | + |
| 97 | + # Read file_length (optional: union[null, long]) |
| 98 | + file_length = None |
| 99 | + if offset < len(data): |
| 100 | + union_index, offset = _read_avro_long(data, offset) |
| 101 | + if union_index == 0: |
| 102 | + file_length = None |
| 103 | + elif union_index == 1: |
| 104 | + file_length, offset = _read_avro_long(data, offset) |
| 105 | + else: |
| 106 | + raise ValueError(f"Invalid union index for file_length: {union_index}") |
| 107 | + |
| 108 | + return StandardKeyMetadata( |
| 109 | + encryption_key=encryption_key, |
| 110 | + aad_prefix=aad_prefix, |
| 111 | + file_length=file_length, |
| 112 | + ) |
| 113 | + |
| 114 | + def serialize(self) -> bytes: |
| 115 | + """Serialize to wire format: ``0x01 version || Avro-encoded fields``.""" |
| 116 | + parts = [bytes([V1])] |
| 117 | + |
| 118 | + # encryption_key (required bytes) |
| 119 | + parts.append(_encode_avro_bytes(self.encryption_key)) |
| 120 | + |
| 121 | + # aad_prefix (union[null, bytes]) |
| 122 | + if self.aad_prefix: |
| 123 | + parts.append(_encode_avro_long(1)) # union index 1 = bytes |
| 124 | + parts.append(_encode_avro_bytes(self.aad_prefix)) |
| 125 | + else: |
| 126 | + parts.append(_encode_avro_long(0)) # union index 0 = null |
| 127 | + |
| 128 | + # file_length (union[null, long]) |
| 129 | + if self.file_length is not None: |
| 130 | + parts.append(_encode_avro_long(1)) # union index 1 = long |
| 131 | + parts.append(_encode_avro_long(self.file_length)) |
| 132 | + else: |
| 133 | + parts.append(_encode_avro_long(0)) # union index 0 = null |
| 134 | + |
| 135 | + return b"".join(parts) |
| 136 | + |
| 137 | + |
| 138 | +def _encode_avro_long(value: int) -> bytes: |
| 139 | + """Encode a long as zigzag-encoded Avro varint.""" |
| 140 | + # Zigzag encode |
| 141 | + n = (value << 1) ^ (value >> 63) |
| 142 | + result = bytearray() |
| 143 | + while n & ~0x7F: |
| 144 | + result.append((n & 0x7F) | 0x80) |
| 145 | + n >>= 7 |
| 146 | + result.append(n & 0x7F) |
| 147 | + return bytes(result) |
| 148 | + |
| 149 | + |
| 150 | +def _encode_avro_bytes(data: bytes) -> bytes: |
| 151 | + """Encode bytes with Avro length prefix.""" |
| 152 | + return _encode_avro_long(len(data)) + data |
0 commit comments