diff --git a/types/email.go b/types/email.go index e0ca71f..3e265be 100644 --- a/types/email.go +++ b/types/email.go @@ -39,6 +39,14 @@ func (e *Email) UnmarshalJSON(data []byte) error { return ErrValidationEmail } + // m.Address is the addr-spec with any quoting removed. For a quoted local + // part such as "a b"@example.com that leaves a string that is no longer an + // addr-spec: MarshalJSON, and any later parse, rejects it or reads a + // different address. Accept only a value that survives its own round trip. + if r, err := mail.ParseAddress(m.Address); err != nil || r.Address != m.Address { + return ErrValidationEmail + } + *e = Email(m.Address) return nil } diff --git a/types/email_test.go b/types/email_test.go index ef31119..b9b6903 100644 --- a/types/email_test.go +++ b/types/email_test.go @@ -176,3 +176,61 @@ func TestEmail_UnmarshalJSON_NullableEmail_Validation(t *testing.T) { }) } } + +func TestEmail_UnmarshalJSON_OnlyAcceptsValuesThatRoundTrip(t *testing.T) { + type requiredEmail struct { + EmailField Email `json:"email"` + } + + testCases := map[string]struct { + jsonStr string + want Email + wantErr error + }{ + "plain address": {jsonStr: `{"email":"user@example.com"}`, want: "user@example.com"}, + "display name is dropped": { + jsonStr: `{"email":"Gaben "}`, + want: "gaben@valvesoftware.com", + }, + "quoted local part with a space": {jsonStr: `{"email":"\"a b\"@example.com"}`, wantErr: ErrValidationEmail}, + "quoted local part with an at sign": { + jsonStr: `{"email":"\"a@b\"@example.com"}`, + wantErr: ErrValidationEmail, + }, + "quoted local part with a comma": {jsonStr: `{"email":"\"a,b\"@example.com"}`, wantErr: ErrValidationEmail}, + "quoted local part with a leading space": { + jsonStr: `{"email":"\" x\"@example.com"}`, + wantErr: ErrValidationEmail, + }, + "quoted local part with a backslash": { + jsonStr: `{"email":"\"a\\\\\"@example.com"}`, + wantErr: ErrValidationEmail, + }, + "quoted local part with angle brackets": { + jsonStr: `{"email":"\"a>,