key.Id +fmt fixes
[epoint] / pkg / document / document.go
1 // Package document implements epoint document parsing and creation.
2 //
3 // An epoint document is an OpenPGP (RFC 4880) clear signed
4 // utf-8 text of key-value pairs.
5 // The body contains a content-type MIME header so the document
6 // can be used in OpenPGP/MIME (RFC 3156) emails.
7 // The format of the key-value pairs is similar to MIME header
8 // fields: keys and values are separated by ": ", repeated keys
9 // are not allowed, long values can be split before a space.
10 //
11 // Example:
12 //
13 // -----BEGIN PGP SIGNED MESSAGE-----
14 // Hash: SHA1
15 //
16 // Content-Type: text/vnd.epoint.type; charset=utf-8
17 //
18 // Key: Value1
19 // Another-Key: Value2
20 // Last-Key: Long
21 //  value that spans
22 //  multiple lines
23 // -----BEGIN PGP SIGNATURE-----
24 //
25 // pgp signature
26 // -----END PGP SIGNATURE-----
27 package document
28
29 // TODO: error wrapper (so reporting to user or creating bounce cert is simple)
30 // TODO: optional fields: exact semantics ("" vs "-" vs nil)
31 // TODO: trailing space handling in ParseFields
32 // TODO: fields of notice (last notice, serial, failure notice,..)
33 // TODO: limits and cert type specific input validation
34 // TODO: hex nonce, uniq nonce vs uniq drawer.nonce
35 // TODO: denom, issuer from key (key representation: armor?)
36
37 import (
38         "bytes"
39         "crypto"
40         "crypto/openpgp"
41         "crypto/openpgp/armor"
42         "crypto/openpgp/packet"
43         "crypto/sha1"
44         "encoding/hex"
45         "fmt"
46         "reflect"
47         "strconv"
48         "strings"
49         "time"
50 )
51
52 // limits
53 const (
54         MaxFields             = 20
55         MaxLineLength         = 160  // 1 sha512 + 1 key (without \n)
56         MaxValueLength        = 1300 // 20 sha256 space separated (without \n)
57         MaxNonceLength        = 20
58         MaxDenominationLength = 100
59 )
60
61 const ClearSignedHeader = "-----BEGIN PGP SIGNED MESSAGE-----"
62
63 // MIME type for epoint documents, see RFC 4288
64 var ContentType = map[string]string{
65         "Draft":      "text/vnd.epoint.draft; charset=utf-8",
66         "Notice":     "text/vnd.epoint.notice; charset=utf-8",
67         "DebitCert":  "text/vnd.epoint.debit; charset=utf-8",
68         "CreditCert": "text/vnd.epoint.credit; charset=utf-8",
69         "BounceCert": "text/vnd.epoint.bounce; charset=utf-8",
70 }
71
72 // OpenPGP signed cleartext document representation
73 type Signed struct {
74         // Sign and CleanSigned sets Hash for FormatSigned
75         // TODO: CreationDate
76         Hash string
77         // Signed text (no dash escape, no trailing space, \n new lines)
78         Body []byte
79         // Armored detached text signature of the Body
80         Signature []byte
81 }
82
83 // parsed epoint document
84 type Document struct {
85         Type   string
86         Fields map[string]string
87         Order  []string
88 }
89
90 var fieldtype = map[string]string{
91         "Amount":             "int",
92         "Authorized-By":      "id",
93         "Balance":            "int",
94         "Beneficiary":        "id",
95         "Date":               "date",
96         "Debit-Cert":         "id",
97         "Denomination":       "text",
98         "Difference":         "int",
99         "Draft":              "id",
100         "Drawer":             "id",
101         "Expiry-Date":        "date",
102         "Holder":             "id",
103         "Issuer":             "id",
104         "Last-Cert":          "id",
105         "Last-Credit-Serial": "int",
106         "Last-Debit-Serial":  "int",
107         "Maturity-Date":      "date",
108         "Nonce":              "id",
109         "Notes":              "text",
110         "References":         "ids",
111         "Serial":             "int",
112 }
113
114 var fieldname = map[string]string{
115         "AuthorizedBy":     "Authorized-By",
116         "DebitCert":        "Debit-Cert",
117         "ExpiryDate":       "Expiry-Date",
118         "LastCert":         "Last-Cert",
119         "LastCreditSerial": "Last-Credit-Serial",
120         "LastDebitSerial":  "Last-Debit-Serial",
121         "MaturityDate":     "Maturity-Date",
122 }
123
124 type Draft struct {
125         Drawer       string
126         Beneficiary  string
127         Amount       int64
128         Denomination string
129         Issuer       string
130         AuthorizedBy string
131         MaturityDate *int64 // optional
132         ExpiryDate   *int64 // optional
133         Nonce        string
134         Notes        *string // optional
135 }
136
137 type Notice struct {
138         Date         int64
139         AuthorizedBy string
140         Notes        *string  // optional
141         References   []string // may be empty (startup notice)
142 }
143
144 type Cert struct {
145         Holder           string
146         Serial           int64
147         Balance          int64
148         Denomination     string
149         Issuer           string
150         Date             int64
151         AuthorizedBy     string
152         Notes            *string // optional
153         LastDebitSerial  int64   // 0 if none
154         LastCreditSerial int64   // 0 if none
155         LastCert         *string // nil if serial == 1
156         References       []string
157         Difference       int64
158         Draft            string
159 }
160
161 type DebitCert struct {
162         Cert
163         Beneficiary string
164 }
165
166 type CreditCert struct {
167         Cert
168         Drawer    string
169         DebitCert string
170 }
171
172 type BounceCert struct {
173         Drawer       string
174         Draft        string
175         LastCert     *string // optional
176         Balance      int64   // 0 if none
177         Date         int64
178         AuthorizedBy string
179         Notes        *string // optional
180         References   []string
181 }
182
183 // Common cert part of a debit or credit cert
184 func ToCert(v interface{}) (cert *Cert, err error) {
185         cert = new(Cert)
186         switch x := v.(type) {
187         case *DebitCert:
188                 cert = &x.Cert
189         case *CreditCert:
190                 cert = &x.Cert
191         default:
192                 err = fmt.Errorf("ToCert: only debit or credit document can be converted to cert")
193         }
194         return
195 }
196
197 func cleanBody(s []byte) []byte {
198         nl := []byte{'\n'}
199         a := bytes.Split(s, nl)
200         for i := range a {
201                 a[i] = bytes.TrimRight(a[i], " \t")
202         }
203         return bytes.Join(a, nl)
204 }
205
206 // sha1 sum of the (cleaned) document body as uppercase hex string
207 func Id(c *Signed) string {
208         h := sha1.New()
209         h.Write(c.Body)
210         return fmt.Sprintf("%040X", h.Sum())
211 }
212
213 // Parse an epoint document without checking the signature and format details
214 func Parse(s []byte) (iv interface{}, c *Signed, err error) {
215         c, err = ParseSigned(s)
216         if err != nil {
217                 return
218         }
219         doc, err := ParseDocument(c.Body)
220         if err != nil {
221                 return
222         }
223         iv, err = ParseStruct(doc)
224         return
225 }
226
227 // Format and sign an epoint document
228 func Format(iv interface{}, key *openpgp.Entity) (s []byte, c *Signed, err error) {
229         doc, err := FormatStruct(iv)
230         if err != nil {
231                 return
232         }
233         body, err := FormatDocument(doc)
234         if err != nil {
235                 return
236         }
237         c, err = Sign(body, key)
238         if err != nil {
239                 return
240         }
241         s, err = FormatSigned(c)
242         return
243 }
244
245 // Verify an epoint document, return the cleaned version as well
246 func Verify(c *Signed, key openpgp.KeyRing) (err error) {
247         msg := bytes.NewBuffer(c.Body)
248         sig := bytes.NewBuffer(c.Signature)
249         // TODO: verify signature
250         _, _ = msg, sig
251         //      _, err = openpgp.CheckArmoredDetachedSignature(key, msg, sig)
252         return
253 }
254
255 // Sign body with given secret key
256 func Sign(body []byte, key *openpgp.Entity) (c *Signed, err error) {
257         c = new(Signed)
258         c.Hash = "SHA256"
259         c.Body = cleanBody(body)
260         w := new(bytes.Buffer)
261         err = openpgp.ArmoredDetachSignText(w, key, bytes.NewBuffer(c.Body))
262         if err != nil {
263                 return
264         }
265         // close armored document with a \n
266         _, _ = w.Write([]byte{'\n'})
267         c.Signature = w.Bytes()
268         return
269 }
270
271 // split a clear signed document into body and armored signature
272 func ParseSigned(s []byte) (c *Signed, err error) {
273         // look for clear signed header
274         for !bytes.HasPrefix(s, []byte(ClearSignedHeader)) {
275                 _, s = getLine(s)
276                 if len(s) == 0 {
277                         err = fmt.Errorf("ParseSigned: clear signed header is missing")
278                         return
279                 }
280         }
281         s = s[len(ClearSignedHeader):]
282         // end of line after the header
283         empty, s := getLine(s)
284         if len(empty) != 0 {
285                 err = fmt.Errorf("ParseSigned: bad clear signed header")
286                 return
287         }
288         // skip all hash headers, section 7.
289         for bytes.HasPrefix(s, []byte("Hash: ")) {
290                 _, s = getLine(s)
291         }
292         // skip empty line
293         empty, s = getLine(s)
294         if len(empty) != 0 {
295                 err = fmt.Errorf("ParseSigned: expected an empty line after armor headers")
296                 return
297         }
298         lines := [][]byte{}
299         for !bytes.HasPrefix(s, []byte("-----BEGIN")) {
300                 var line []byte
301                 line, s = getLine(s)
302                 // dash unescape, section 7.1.
303                 if bytes.HasPrefix(line, []byte("- ")) {
304                         line = line[2:]
305                 }
306                 // empty values are not supported: "Key: \n"
307                 lines = append(lines, bytes.TrimRight(line, " \t"))
308         }
309         c = new(Signed)
310         // last line is not closed by \n
311         c.Body = bytes.Join(lines, []byte("\n"))
312         // signature is just the rest of the input data
313         c.Signature = s
314         return
315 }
316
317 // clean up, check and reencode signature
318 // used on drafts before calculating the signed document hash
319 func CleanSigned(c *Signed) (err error) {
320         b, err := armor.Decode(bytes.NewBuffer(c.Signature))
321         if err != nil {
322                 return
323         }
324         if b.Type != openpgp.SignatureType {
325                 err = fmt.Errorf("CleanSigned: invalid armored signature type")
326                 return
327         }
328         p, err := packet.Read(b.Body)
329         if err != nil {
330                 return
331         }
332         sig, ok := p.(*packet.Signature)
333         if !ok {
334                 err = fmt.Errorf("CleanSigned: invalid signature packet")
335                 return
336         }
337         // section 5.2.3
338         if sig.SigType != packet.SigTypeText {
339                 err = fmt.Errorf("CleanSigned: expected text signature")
340                 return
341         }
342         switch sig.Hash {
343         case crypto.SHA1:
344                 c.Hash = "SHA1"
345         case crypto.SHA256:
346                 c.Hash = "SHA256"
347         default:
348                 err = fmt.Errorf("CleanSigned: expected SHA1 or SHA256 signature hash")
349                 return
350         }
351         // TODO: check CreationTime and other subpackets
352         if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 {
353                 err = fmt.Errorf("CleanSigned: signature must not expire")
354                 return
355         }
356         out := new(bytes.Buffer)
357         w, err := armor.Encode(out, openpgp.SignatureType, nil)
358         if err != nil {
359                 return
360         }
361         err = sig.Serialize(w)
362         if err != nil {
363                 return
364         }
365         err = w.Close()
366         if err != nil {
367                 return
368         }
369         c.Signature = out.Bytes()
370         return
371 }
372
373 // create clear signed document
374 func FormatSigned(c *Signed) (data []byte, err error) {
375         s := ClearSignedHeader + "\n"
376         if c.Hash != "" {
377                 s += "Hash: " + c.Hash + "\n"
378         }
379         s += "\n"
380         s += string(c.Body)
381         s += "\n"
382         s += string(c.Signature)
383         data = []byte(s)
384         return
385 }
386
387 // parse type and fields of a document body
388 func ParseDocument(body []byte) (doc *Document, err error) {
389         // parse content type header first
390         fields, s, err := ParseFields(body)
391         if err != nil {
392                 return
393         }
394         ctype, ok := fields["Content-Type"]
395         if len(fields) != 1 || !ok {
396                 return nil, fmt.Errorf("ParseBody: expected a single Content-Type header field")
397         }
398         doc = new(Document)
399         for k, v := range ContentType {
400                 if ctype == v {
401                         doc.Type = k
402                         break
403                 }
404         }
405         if doc.Type == "" {
406                 return nil, fmt.Errorf("ParseBody: unknown Content-Type: %s", ctype)
407         }
408         // TODO: doc.Order
409         doc.Fields, s, err = ParseFields(s)
410         if err == nil && len(s) > 0 {
411                 err = fmt.Errorf("ParseBody: extra data after fields: %q", s)
412         }
413         return
414 }
415
416 // create document body
417 func FormatDocument(doc *Document) (body []byte, err error) {
418         ctype, ok := ContentType[doc.Type]
419         if !ok {
420                 err = fmt.Errorf("FormatDocument: unknown document type: %s", doc.Type)
421                 return
422         }
423         s := "Content-Type: " + ctype + "\n\n"
424         for _, k := range doc.Order {
425                 s += k + ": " + doc.Fields[k] + "\n"
426         }
427         return []byte(s), nil
428 }
429
430 // parse doc fields into a struct according to the document type
431 func parseStruct(v reflect.Value, fields map[string]string, seen map[string]bool) (err error) {
432         t := v.Type()
433         n := v.NumField()
434         for i := 0; i < n && err == nil; i++ {
435                 ft := t.Field(i)
436                 fv := v.Field(i)
437                 if ft.Anonymous && fv.Kind() == reflect.Struct {
438                         err = parseStruct(fv, fields, seen)
439                         continue
440                 }
441                 key := fieldname[ft.Name]
442                 if key == "" {
443                         key = ft.Name
444                 }
445                 s, ok := fields[key]
446                 if !ok {
447                         if fv.Kind() == reflect.Ptr {
448                                 // missing optional key: leave the pointer as nil
449                                 continue
450                         }
451                         return fmt.Errorf("ParseStruct: field %s of %s is missing\n", key, t.Name())
452                 }
453                 seen[key] = true
454                 if fv.Kind() == reflect.Ptr {
455                         if s == "" || s == "-" {
456                                 // TODO
457                                 // empty optional key: same as missing
458                                 continue
459                         }
460                         fv.Set(reflect.New(fv.Type().Elem()))
461                         fv = fv.Elem()
462                 }
463                 switch fieldtype[key] {
464                 case "id":
465                         var val string
466                         val, err = parseId(s)
467                         fv.SetString(val)
468                 case "text":
469                         var val string
470                         val, err = parseString(s)
471                         fv.SetString(val)
472                 case "int":
473                         var val int64
474                         val, err = strconv.Atoi64(s)
475                         fv.SetInt(val)
476                 case "date":
477                         var val int64
478                         val, err = parseDate(s)
479                         fv.SetInt(val)
480                 case "ids":
481                         // TODO: empty slice?
482                         ids := strings.Split(s, " ")
483                         val := make([]string, len(ids))
484                         for j, id := range ids {
485                                 val[j], err = parseId(id)
486                                 if err != nil {
487                                         return
488                                 }
489                         }
490                         fv.Set(reflect.ValueOf(val))
491                 default:
492                         panic("bad field type " + key + " " + fieldtype[key])
493                 }
494         }
495         return
496 }
497
498 // ParseStruct parses an epoint document and returns a struct representation
499 func ParseStruct(doc *Document) (iv interface{}, err error) {
500         switch doc.Type {
501         case "Draft":
502                 iv = new(Draft)
503         case "Notice":
504                 iv = new(Notice)
505         case "DebitCert":
506                 iv = new(DebitCert)
507         case "CreditCert":
508                 iv = new(CreditCert)
509         case "BounceCert":
510                 iv = new(BounceCert)
511         default:
512                 err = fmt.Errorf("ParseStruct: unkown doc type: %s", doc.Type)
513                 return
514         }
515         seen := make(map[string]bool)
516         err = parseStruct(reflect.ValueOf(iv).Elem(), doc.Fields, seen)
517         if err != nil {
518                 return
519         }
520         if len(doc.Fields) != len(seen) {
521                 for f := range doc.Fields {
522                         if !seen[f] {
523                                 err = fmt.Errorf("ParseStruct: unknown field %s in %s", f, doc.Type)
524                                 return
525                         }
526                 }
527         }
528         return
529 }
530
531 // turn a struct into a document
532 func formatStruct(v reflect.Value, doc *Document) (err error) {
533         t := v.Type()
534         n := v.NumField()
535         for i := 0; i < n; i++ {
536                 ft := t.Field(i)
537                 fv := v.Field(i)
538                 if ft.Anonymous && fv.Kind() == reflect.Struct {
539                         err = formatStruct(fv, doc)
540                         if err != nil {
541                                 return
542                         }
543                         continue
544                 }
545                 key := fieldname[ft.Name]
546                 if key == "" {
547                         key = ft.Name
548                 }
549                 val := ""
550                 if fv.Kind() == reflect.Ptr {
551                         if fv.IsNil() {
552                                 // keep empty optional fields but mark them
553                                 val = "-"
554                                 goto setval
555                         }
556                         fv = fv.Elem()
557                 }
558                 switch fieldtype[key] {
559                 case "id":
560                         val = formatId(fv.String())
561                 case "text":
562                         val = formatString(fv.String())
563                 case "int":
564                         val = strconv.Itoa64(fv.Int())
565                 case "date":
566                         val = formatDate(fv.Int())
567                 case "ids":
568                         k := fv.Len()
569                         for j := 0; j < k; j++ {
570                                 if j > 0 {
571                                         val += "\n "
572                                 }
573                                 val += formatId(fv.Index(j).String())
574                         }
575                 default:
576                         panic("bad field type " + key + " " + fieldtype[key])
577                 }
578         setval:
579                 doc.Fields[key] = val
580                 doc.Order = append(doc.Order, key)
581         }
582         return
583 }
584
585 // FormatStruct turns a struct into a document
586 func FormatStruct(iv interface{}) (doc *Document, err error) {
587         v := reflect.ValueOf(iv)
588         if v.Kind() != reflect.Ptr || v.IsNil() || v.Elem().Kind() != reflect.Struct {
589                 panic("input is not a pointer to struct")
590         }
591         doc = new(Document)
592         doc.Type = v.Elem().Type().Name()
593         doc.Fields = make(map[string]string)
594         err = formatStruct(v.Elem(), doc)
595         return
596 }
597
598 // ParseFields parses a key value sequence into a fields map
599 func ParseFields(s []byte) (fields map[string]string, rest []byte, err error) {
600         rest = s
601         fields = make(map[string]string)
602         key := ""
603         // \n is optional after the last field and an extra \n is allowed as well
604         for len(rest) > 0 {
605                 var line []byte
606                 line, rest = getLine(rest)
607                 // empty line after the last field is consumed
608                 if len(line) == 0 {
609                         break
610                 }
611                 if line[0] == ' ' && key != "" {
612                         // "Key: v1\n v2\n" is equivalent to "Key: v1 v2\n"
613                         fields[key] += string(line)
614                         continue
615                 }
616                 if line[0] < 'A' || line[0] > 'Z' {
617                         err = fmt.Errorf("ParseFields: field name must start with an upper-case ascii letter")
618                         return
619                 }
620                 i := bytes.IndexByte(line, ':')
621                 if i < 0 {
622                         err = fmt.Errorf("ParseFields: missing ':'")
623                         return
624                 }
625                 key = string(line[:i])
626                 if _, ok := fields[key]; ok {
627                         err = fmt.Errorf("ParseFields: repeated fields are not allowed")
628                         return
629                 }
630                 fields[key] = string(line[i+1:])
631         }
632         for key, v := range fields {
633                 // either a single space follows ':' or the value is empty
634                 // good: "Key:\n", "Key:\n value\n", "Key: value\n", "Key: v1\n v2\n"
635                 // bad: "Key:value\n", "Key: \nvalue\n"
636                 // bad but not checked here: "Key: \n", "Key: value \n", "Key:\n \n value\n"
637                 if len(v) == 0 {
638                         continue
639                 }
640                 if v[0] != ' ' {
641                         err = fmt.Errorf("ParseFields: ':' is not followed by ' '")
642                         return
643                 }
644                 fields[key] = v[1:]
645         }
646         return
647 }
648
649 // TODO: limit errors
650
651 func parseId(s string) (string, error) {
652         // check if hex decodable
653         // TODO: length check
654         dst := make([]byte, len(s)/2)
655         _, err := hex.Decode(dst, []byte(s))
656         return s, err
657 }
658
659 func formatId(s string) string {
660         return s
661 }
662
663 func parseString(s string) (string, error) {
664         if len(s) > MaxValueLength {
665                 return "", fmt.Errorf("parseString: length limit is exceeded")
666         }
667         return s, nil
668 }
669
670 func formatString(s string) string {
671         return s
672 }
673
674 func parseDate(s string) (int64, error) {
675         // TODO: fractional seconds?
676         t, err := time.Parse(time.RFC3339, s)
677         if err != nil {
678                 return 0, err
679         }
680         return t.Seconds(), nil
681 }
682
683 func formatDate(i int64) string {
684         return time.SecondsToUTC(i).Format(time.RFC3339)
685 }
686
687 func getLine(data []byte) (line, rest []byte) {
688         i := bytes.IndexByte(data, '\n')
689         j := i + 1
690         if i < 0 {
691                 i = len(data)
692                 j = i
693         } else if i > 0 && data[i-1] == '\r' {
694                 i--
695         }
696         return data[:i], data[j:]
697 }