opaque_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package packet
  5. import (
  6. "bytes"
  7. "code.google.com/p/go.crypto/openpgp/armor"
  8. "io"
  9. "testing"
  10. )
  11. // This key contains version 2 public key and signature packets.
  12. // If these are ever supported, this test will need to be updated
  13. // with bad packets that won't parse.
  14. const UnsupportedKeyArmor = `-----BEGIN PGP PUBLIC KEY BLOCK-----
  15. Version: SKS 1.0.10
  16. mI0CLnoYogAAAQQA1qwA2SuJwfQ5bCQ6u5t20ulnOtY0gykf7YjiK4LiVeRBwHjGq7v30tGV
  17. 5Qti7qqRW4Ww7CDCJc4sZMFnystucR2vLkXaSoNWoFm4Fg47NiisDdhDezHwbVPW6OpCFNSi
  18. ZAamtj4QAUBu8j4LswafrJqZqR9336/V3g8Yil2l48kABRG0J0FybWluIE0uIFdhcmRhIDx3
  19. YXJkYUBuZXBoaWxpbS5ydWhyLmRlPoiVAgUQLok2xwXR6zmeWEiZAQE/DgP/WgxPQh40/Po4
  20. gSkWZCDAjNdph7zexvAb0CcUWahcwiBIgg3U5ErCx9I5CNVA9U+s8bNrDZwgSIeBzp3KhWUx
  21. 524uhGgm6ZUTOAIKA6CbV6pfqoLpJnRYvXYQU5mIWsNa99wcu2qu18OeEDnztb7aLA6Ra9OF
  22. YFCbq4EjXRoOrYM=
  23. =LPjs
  24. -----END PGP PUBLIC KEY BLOCK-----`
  25. // Test packet.Read error handling in OpaquePacket.Parse,
  26. // which attempts to re-read an OpaquePacket as a supported
  27. // Packet type.
  28. func TestOpaqueParseReason(t *testing.T) {
  29. armorBlock, err := armor.Decode(bytes.NewBufferString(UnsupportedKeyArmor))
  30. if err != nil {
  31. t.Fatalf("armor Decode failed: %v", err)
  32. }
  33. or := NewOpaqueReader(armorBlock.Body)
  34. count := 0
  35. badPackets := 0
  36. var uid *UserId
  37. for {
  38. op, err := or.Next()
  39. if err == io.EOF {
  40. break
  41. } else if err != nil {
  42. t.Errorf("#%d: opaque read error: %v", count, err)
  43. break
  44. }
  45. // try to parse opaque packet
  46. p, err := op.Parse()
  47. switch pkt := p.(type) {
  48. case *UserId:
  49. uid = pkt
  50. case *OpaquePacket:
  51. // If an OpaquePacket can't re-parse, packet.Read
  52. // certainly had its reasons.
  53. if pkt.Reason == nil {
  54. t.Errorf("#%d: opaque packet, no reason", count)
  55. } else {
  56. badPackets++
  57. }
  58. }
  59. count++
  60. }
  61. const expectedBad = 2
  62. // Test post-conditions, make sure we actually parsed packets as expected.
  63. if badPackets != expectedBad {
  64. t.Errorf("unexpected # unparseable packets: %d (want %d)", badPackets, expectedBad)
  65. }
  66. if uid == nil {
  67. t.Errorf("failed to find expected UID in unsupported keyring")
  68. } else if uid.Id != "Armin M. Warda <warda@nephilim.ruhr.de>" {
  69. t.Errorf("unexpected UID: %v", uid.Id)
  70. }
  71. }