1 // Package document implements epoint document parsing and creation.
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 are 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.
13 // -----BEGIN PGP SIGNED MESSAGE-----
16 // Content-Type: text/plain.epoint.type; charset=utf-8
19 // Another-Key: Value2
23 // -----BEGIN PGP SIGNATURE-----
26 // -----END PGP SIGNATURE-----
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: fix Cert mess
40 "crypto/openpgp/armor"
41 "crypto/openpgp/packet"
54 MaxLineLength = 160 // 1 sha512 + 1 key (without \n)
55 MaxValueLength = 1300 // 20 sha256 space separated (without \n)
57 MaxDenominationLength = 100
60 const ClearSignedHeader = "-----BEGIN PGP SIGNED MESSAGE-----"
62 // MIME type for epoint documents, see RFC 4288
63 var ContentType = map[string]string{
64 "Draft": "text/vnd.epoint.draft; charset=utf-8",
65 "Notice": "text/vnd.epoint.notice; charset=utf-8",
66 "DebitCert": "text/vnd.epoint.debit; charset=utf-8",
67 "CreditCert": "text/vnd.epoint.credit; charset=utf-8",
68 "BounceCert": "text/vnd.epoint.bounce; charset=utf-8",
71 // OpenPGP signed cleartext document representation
73 // Sign and CleanSigned sets Hash for FormatSigned
76 // Signed text (no dash escape, no trailing space, \n new lines)
78 // Armored detached text signature of the Body
82 // parsed epoint document
83 type Document struct {
85 Fields map[string]string
89 var fieldtype = map[string]string{
91 "Authorized-By": "id",
96 "Denomination": "text",
100 "Expiry-Date": "date",
104 "Last-Credit-Serial": "int",
105 "Last-Debit-Serial": "int",
106 "Maturity-Date": "date",
113 var fieldname = map[string]string{
114 "AuthorizedBy": "Authorized-By",
115 "DebitCert": "Debit-Cert",
116 "ExpiryDate": "Expiry-Date",
117 "LastCert": "Last-Cert",
118 "LastCreditSerial": "Last-Credit-Serial",
119 "LastDebitSerial": "Last-Debit-Serial",
120 "MaturityDate": "Maturity-Date",
130 MaturityDate *int64 // optional
131 ExpiryDate *int64 // optional
132 Nonce *string // optional
133 Notes *string // optional
139 Notes *string // optional
140 References []string // may be empty (startup notice)
153 Beneficiary *string // only in debit cert
154 Drawer *string // only in credit cert
155 DebitCert *string // only in credit cert
157 Notes *string // optional
158 LastDebitSerial int64 // 0 if none
159 LastCreditSerial int64 // 0 if none
160 LastCert *string // nil if serial == 1
164 type DebitCert struct {
175 Notes *string // optional
176 LastDebitSerial int64 // 0 if none
177 LastCreditSerial int64 // 0 if none
178 LastCert *string // nil if serial == 1
182 type CreditCert struct {
194 Notes *string // optional
195 LastDebitSerial int64 // 0 if none
196 LastCreditSerial int64 // 0 if none
197 LastCert *string // ? if serial == 1
201 type BounceCert struct {
204 LastCert *string // optional
205 Balance int64 // 0 if none
208 Notes *string // optional
212 func ToCert(v interface{}) (cert *Cert, err error) {
214 switch x := v.(type) {
217 cert.Beneficiary = &x.Beneficiary
219 cert.Holder = x.Holder
220 cert.Serial = x.Serial
221 cert.Balance = x.Balance
222 cert.Denomination = x.Denomination
223 cert.Issuer = x.Issuer
225 cert.Difference = x.Difference
227 cert.AuthorizedBy = x.AuthorizedBy
229 cert.LastDebitSerial = x.LastDebitSerial
230 cert.LastCreditSerial = x.LastCreditSerial
231 cert.LastCert = x.LastCert
232 cert.References = x.References
236 cert.Drawer = &x.Drawer
237 cert.DebitCert = &x.DebitCert
239 cert.Holder = x.Holder
240 cert.Serial = x.Serial
241 cert.Balance = x.Balance
242 cert.Denomination = x.Denomination
243 cert.Issuer = x.Issuer
245 cert.Difference = x.Difference
247 cert.AuthorizedBy = x.AuthorizedBy
249 cert.LastDebitSerial = x.LastDebitSerial
250 cert.LastCreditSerial = x.LastCreditSerial
251 cert.LastCert = x.LastCert
252 cert.References = x.References
254 err = fmt.Errorf("ToCert: only debit or credit document can be converted to cert")
259 // sha1 sum of the (cleaned) document body as uppercase hex string
260 func Id(c *Signed) string {
263 return fmt.Sprintf("%040X", h.Sum())
266 // parse an epoint document without checking the signature and format details
267 func Parse(s []byte) (iv interface{}, c *Signed, err error) {
268 c, err = ParseSigned(s)
272 doc, err := ParseDocument(c.Body)
276 iv, err = ParseStruct(doc)
280 // format and sign an epoint document
281 func Format(iv interface{}, key *openpgp.Entity) (s []byte, c *Signed, err error) {
282 doc, err := FormatStruct(iv)
286 body, err := FormatDocument(doc)
290 c, err = Sign(body, key)
294 s, err = FormatSigned(c)
298 // verify an epoint document, return the cleaned version as well
299 func Verify(c *Signed, key openpgp.KeyRing) (err error) {
300 msg := bytes.NewBuffer(c.Body)
301 sig := bytes.NewBuffer(c.Signature)
302 // TODO: verify signature
304 // _, err = openpgp.CheckArmoredDetachedSignature(key, msg, sig)
308 // sign body with given secret key
309 func Sign(body []byte, key *openpgp.Entity) (c *Signed, err error) {
313 w := new(bytes.Buffer)
314 err = openpgp.ArmoredDetachSignText(w, key, bytes.NewBuffer(c.Body))
315 c.Signature = w.Bytes()
319 // split a clear signed document into body and armored signature
320 func ParseSigned(s []byte) (c *Signed, err error) {
321 // look for clear signed header
322 for !bytes.HasPrefix(s, []byte(ClearSignedHeader)) {
325 err = fmt.Errorf("ParseSigned: clear signed header is missing")
329 s = s[len(ClearSignedHeader):]
330 // end of line after the header
331 empty, s := getLine(s)
333 err = fmt.Errorf("ParseSigned: bad clear signed header")
336 // skip all hash headers, section 7.
337 for bytes.HasPrefix(s, []byte("Hash: ")) {
341 empty, s = getLine(s)
343 err = fmt.Errorf("ParseSigned: expected an empty line after armor headers")
347 for !bytes.HasPrefix(s, []byte("-----BEGIN")) {
350 // dash unescape, section 7.1.
351 if bytes.HasPrefix(line, []byte("- ")) {
354 // empty values are not supported: "Key: \n"
355 lines = append(lines, bytes.TrimRight(line, " \t"))
358 // last line is not closed by \n
359 c.Body = bytes.Join(lines, []byte("\n"))
360 // signature is just the rest of the input data
365 // clean up, check and reencode signature
366 // used on drafts before calculating the signed document hash
367 func CleanSigned(c *Signed) (err error) {
368 b, err := armor.Decode(bytes.NewBuffer(c.Signature))
372 if b.Type != openpgp.SignatureType {
373 err = fmt.Errorf("CleanSigned: invalid armored signature type")
376 p, err := packet.Read(b.Body)
380 sig, ok := p.(*packet.Signature)
382 err = fmt.Errorf("CleanSigned: invalid signature packet")
386 if sig.SigType != packet.SigTypeText {
387 err = fmt.Errorf("CleanSigned: expected text signature")
396 err = fmt.Errorf("CleanSigned: expected SHA1 or SHA256 signature hash")
399 // TODO: check CreationTime and other subpackets
400 if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 {
401 err = fmt.Errorf("CleanSigned: signature must not expire")
404 out := new(bytes.Buffer)
405 w, err := armor.Encode(out, openpgp.SignatureType, nil)
409 err = sig.Serialize(w)
417 c.Signature = out.Bytes()
421 // create clear signed document
422 func FormatSigned(c *Signed) (data []byte, err error) {
423 s := ClearSignedHeader + "\n"
425 s += "Hash: " + c.Hash + "\n"
430 s += string(c.Signature)
435 // parse type and fields of a document body
436 func ParseDocument(body []byte) (doc *Document, err error) {
437 // parse content type header first
438 fields, s, err := ParseFields(body)
442 ctype, ok := fields["Content-Type"]
443 if len(fields) != 1 || !ok {
444 return nil, fmt.Errorf("ParseBody: expected a single Content-Type header field")
447 for k, v := range ContentType {
454 return nil, fmt.Errorf("ParseBody: unknown Content-Type: %s", ctype)
457 doc.Fields, s, err = ParseFields(s)
458 if err == nil && len(s) > 0 {
459 err = fmt.Errorf("ParseBody: extra data after fields: %q", s)
464 // create document body
465 func FormatDocument(doc *Document) (body []byte, err error) {
466 ctype, ok := ContentType[doc.Type]
468 err = fmt.Errorf("FormatDocument: unknown document type: %s", doc.Type)
471 s := "Content-Type: " + ctype + "\n\n"
472 for _, k := range doc.Order {
473 s += k + ": " + doc.Fields[k] + "\n"
475 return []byte(s), nil
478 // parse doc fields into a struct according to the document type
479 func ParseStruct(doc *Document) (iv interface{}, err error) {
492 err = fmt.Errorf("ParseStruct: unkown doc type: %s", doc.Type)
495 seen := make(map[string]bool)
496 v := reflect.ValueOf(iv).Elem()
500 for i := 0; i < n; i++ {
503 key := fieldname[ft.Name]
508 s, ok := doc.Fields[key]
510 if fv.Kind() == reflect.Ptr {
511 // missing optional key: leave the pointer as nil
515 return nil, fmt.Errorf("ParseStruct: field %s of %s is missing\n", key, t.Name())
517 if fv.Kind() == reflect.Ptr {
518 if s == "" || s == "-" {
520 // empty optional key: same as missing
523 fv.Set(reflect.New(fv.Type().Elem()))
526 switch fieldtype[key] {
529 val, err = parseId(s)
533 val, err = parseString(s)
537 val, err = strconv.Atoi64(s)
541 val, err = parseDate(s)
544 // TODO: empty slice?
545 ids := strings.Split(s, " ")
546 val := make([]string, len(ids))
547 for j, id := range ids {
548 val[j], err = parseId(id)
553 fv.Set(reflect.ValueOf(val))
555 panic("bad field type " + key + " " + fieldtype[key])
561 if len(doc.Fields)+nokey != n {
562 for k := range doc.Fields {
564 err = fmt.Errorf("ParseStruct: unknown field %s in %s", k, t.Name())
572 // turn a struct into a document
573 func FormatStruct(iv interface{}) (doc *Document, err error) {
574 v := reflect.ValueOf(iv)
575 if v.Kind() != reflect.Ptr || v.IsNil() || v.Elem().Kind() != reflect.Struct {
576 panic("input is not a pointer to struct")
583 doc.Fields = make(map[string]string)
584 for i := 0; i < n; i++ {
587 key := fieldname[ft.Name]
592 if fv.Kind() == reflect.Ptr {
594 // keep empty optional fields but mark them
600 switch fieldtype[key] {
602 val = formatId(fv.String())
604 val = formatString(fv.String())
606 val = strconv.Itoa64(fv.Int())
608 val = formatDate(fv.Int())
611 for j := 0; j < k; j++ {
615 val += formatId(fv.Index(j).String())
618 panic("bad field type " + key + " " + fieldtype[key])
621 doc.Fields[key] = val
622 doc.Order = append(doc.Order, key)
627 func ParseFields(s []byte) (fields map[string]string, rest []byte, err error) {
629 fields = make(map[string]string)
631 // \n is optional after the last field and an extra \n is allowed as well
634 line, rest = getLine(rest)
635 // empty line after the last field is consumed
639 if line[0] == ' ' && key != "" {
640 // "Key: v1\n v2\n" is equivalent to "Key: v1 v2\n"
641 fields[key] += string(line)
644 if line[0] < 'A' || line[0] > 'Z' {
645 err = fmt.Errorf("ParseFields: field name must start with an upper-case ascii letter")
648 i := bytes.IndexByte(line, ':')
650 err = fmt.Errorf("ParseFields: missing ':'")
653 key = string(line[:i])
654 if _, ok := fields[key]; ok {
655 err = fmt.Errorf("ParseFields: repeated fields are not allowed")
658 fields[key] = string(line[i+1:])
660 for key, v := range fields {
661 // either a single space follows ':' or the value is empty
662 // good: "Key:\n", "Key:\n value\n", "Key: value\n", "Key: v1\n v2\n"
663 // bad: "Key:value\n", "Key: \nvalue\n"
664 // bad but not checked here: "Key: \n", "Key: value \n", "Key:\n \n value\n"
669 err = fmt.Errorf("ParseFields: ':' is not followed by ' '")
677 // TODO: limit errors
679 func parseId(s string) (string, error) {
680 // check if hex decodable
681 // TODO: length check
682 dst := make([]byte, len(s)/2)
683 _, err := hex.Decode(dst, []byte(s))
687 func formatId(s string) string {
691 func parseString(s string) (string, error) {
692 if len(s) > MaxValueLength {
693 return "", fmt.Errorf("parseString: length limit is exceeded")
698 func formatString(s string) string {
702 func parseDate(s string) (int64, error) {
703 // TODO: fractional seconds?
704 t, err := time.Parse(time.RFC3339, s)
708 return t.Seconds(), nil
711 func formatDate(i int64) string {
712 return time.SecondsToUTC(i).Format(time.RFC3339)
715 func getLine(data []byte) (line, rest []byte) {
716 i := bytes.IndexByte(data, '\n')
721 } else if i > 0 && data[i-1] == '\r' {
724 return data[:i], data[j:]