Decode and fully validate canonical signed bytes. Rejects wrong magic, trailing bytes, unsupported versions, malformed or non-canonical encodings, raw-object mismatches, and any recomputation failure of a bound derived field.
(bytes: &[u8])
| 503 | /// or non-canonical encodings, raw-object mismatches, and any |
| 504 | /// recomputation failure of a bound derived field. |
| 505 | pub fn decode(bytes: &[u8]) -> Result<Self, BindingDecodeError> { |
| 506 | let minimum = BINDING_MAGIC.len() + 64 + 1; |
| 507 | if bytes.len() < minimum { |
| 508 | return Err(BindingDecodeError::Truncated { |
| 509 | length: bytes.len(), |
| 510 | }); |
| 511 | } |
| 512 | if &bytes[..BINDING_MAGIC.len()] != BINDING_MAGIC { |
| 513 | return Err(BindingDecodeError::BadMagic); |
| 514 | } |
| 515 | let signature_start = bytes.len() - 64; |
| 516 | let payload = postcard::from_bytes::<GitStateBindingPayload>( |
| 517 | &bytes[BINDING_MAGIC.len()..signature_start], |
| 518 | ) |
| 519 | .map_err(|error| BindingDecodeError::Malformed { |
| 520 | reason: error.to_string(), |
| 521 | })?; |
| 522 | // Canonicality: re-encoding must reproduce the exact payload region, |
| 523 | // so no alternative encoding of the same fields exists and no bytes |
| 524 | // are smuggled between payload and signature. |
| 525 | let reencoded = |
| 526 | payload |
| 527 | .canonical_payload_bytes() |
| 528 | .map_err(|error| BindingDecodeError::Malformed { |
| 529 | reason: error.to_string(), |
| 530 | })?; |
| 531 | if bytes.len() != reencoded.len() + 64 || reencoded.as_slice() != &bytes[..reencoded.len()] |
| 532 | { |
| 533 | return Err(BindingDecodeError::NonCanonical); |
| 534 | } |
| 535 | let signature = <[u8; 64]>::try_from(&bytes[signature_start..]).map_err(|_| { |
| 536 | BindingDecodeError::Malformed { |
| 537 | reason: "signature is not exactly 64 bytes".to_string(), |
| 538 | } |
| 539 | })?; |
| 540 | let binding = Self { |
| 541 | payload, |
| 542 | payload_bytes: bytes[..signature_start].to_vec(), |
| 543 | signature, |
| 544 | }; |
| 545 | binding |
| 546 | .payload |
| 547 | .validate() |
| 548 | .map_err(BindingDecodeError::Invalid)?; |
| 549 | Ok(binding) |
| 550 | } |
| 551 | |
| 552 | /// Verify the Ed25519 signature against the carried verifying key. |
| 553 | pub fn verify_signature(&self) -> Result<(), BindingDecodeError> { |