requests.go 25.5 KB
Newer Older
1
package irma
2 3

import (
4
	"encoding/json"
5
	"fmt"
6
	"io/ioutil"
7 8 9
	"strconv"
	"time"

10
	"github.com/bwesterb/go-atum"
11
	"github.com/dgrijalva/jwt-go"
Sietse Ringers's avatar
Sietse Ringers committed
12
	"github.com/go-errors/errors"
13
	"github.com/privacybydesign/gabi"
14
	"github.com/privacybydesign/gabi/big"
15
	"github.com/privacybydesign/irmago/internal/fs"
Sietse Ringers's avatar
Sietse Ringers committed
16
)
17

18 19
// BaseRequest contains the context and nonce for an IRMA session.
type BaseRequest struct {
20 21
	// Denotes session type, must be "disclosing", "signing" or "issuing"
	Type Action `json:"type"`
22
	// Message version. Current version is 2.
23
	Version int `json:"v,omitempty"`
24

25
	// Chosen by the IRMA server during the session
26 27 28
	Context         *big.Int         `json:"context,omitempty"`
	Nonce           *big.Int         `json:"nonce,omitempty"`
	ProtocolVersion *ProtocolVersion `json:"protocolVersion,omitempty"`
29 30 31

	// cache for Identifiers() method
	ids *IrmaIdentifierSet
Sietse Ringers's avatar
Sietse Ringers committed
32 33
}

34 35
// An AttributeCon is only satisfied if all of its containing attribute requests are satisfied.
type AttributeCon []AttributeRequest
36

37 38
// An AttributeDisCon is satisfied if at least one of its containing AttributeCon is satisfied.
type AttributeDisCon []AttributeCon
39

40 41
// AttributeConDisCon is only satisfied if all of the containing AttributeDisCon are satisfied.
type AttributeConDisCon []AttributeDisCon
42

43 44
// A DisclosureRequest is a request to disclose certain attributes. Construct new instances using
// NewDisclosureRequest().
45
type DisclosureRequest struct {
46
	BaseRequest
47 48 49

	Disclose AttributeConDisCon       `json:"disclose"`
	Labels   map[int]TranslatedString `json:"labels"`
50 51
}

52 53
// A SignatureRequest is a a request to sign a message with certain attributes. Construct new
// instances using NewSignatureRequest().
54
type SignatureRequest struct {
55
	DisclosureRequest
56
	Message string `json:"message"`
57 58
}

Sietse Ringers's avatar
Sietse Ringers committed
59
// An IssuanceRequest is a request to issue certain credentials,
60 61
// optionally also asking for certain attributes to be simultaneously disclosed. Construct new
// instances using NewIssuanceRequest().
62
type IssuanceRequest struct {
63
	DisclosureRequest
64
	Credentials []*CredentialRequest `json:"credentials"`
Tomas's avatar
Tomas committed
65 66 67

	// Derived data
	CredentialInfoList        CredentialInfoList `json:",omitempty"`
68
	RemovalCredentialInfoList CredentialInfoList `json:",omitempty"`
69 70
}

Sietse Ringers's avatar
Sietse Ringers committed
71 72
// A CredentialRequest contains the attributes and metadata of a credential
// that will be issued in an IssuanceRequest.
73
type CredentialRequest struct {
74 75
	Validity         *Timestamp               `json:"validity,omitempty"`
	KeyCounter       int                      `json:"keyCounter,omitempty"`
76 77
	CredentialTypeID CredentialTypeIdentifier `json:"credential"`
	Attributes       map[string]string        `json:"attributes"`
Sietse Ringers's avatar
Sietse Ringers committed
78 79
}

80 81 82 83
// SessionRequest instances contain all information the irmaclient needs to perform an IRMA session.
type SessionRequest interface {
	Validator
	Base() *BaseRequest
84
	GetNonce(timestamp *atum.Timestamp) *big.Int
85 86 87
	Disclosure() *DisclosureRequest
	Identifiers() *IrmaIdentifierSet
	Action() Action
88
	Legacy() (SessionRequest, error)
89 90 91 92 93
}

// Timestamp is a time.Time that marshals to Unix timestamps.
type Timestamp time.Time

Sietse Ringers's avatar
Sietse Ringers committed
94 95 96 97 98 99 100
// ServerJwt contains standard JWT fields.
type ServerJwt struct {
	Type       string    `json:"sub"`
	ServerName string    `json:"iss"`
	IssuedAt   Timestamp `json:"iat"`
}

101 102
// RequestorBaseRequest contains fields present in all RequestorRequest types
// with which the requestor configures an IRMA session.
103
type RequestorBaseRequest struct {
Sietse Ringers's avatar
Sietse Ringers committed
104 105 106
	ResultJwtValidity int    `json:"validity,omitempty"`    // Validity of session result JWT in seconds
	ClientTimeout     int    `json:"timeout,omitempty"`     // Wait this many seconds for the IRMA app to connect before the session times out
	CallbackUrl       string `json:"callbackUrl,omitempty"` // URL to post session result to
107 108
}

109 110
// RequestorRequest is the message with which requestors start an IRMA session. It contains a
// SessionRequest instance for the irmaclient along with extra fields in a RequestorBaseRequest.
111 112 113
type RequestorRequest interface {
	Validator
	SessionRequest() SessionRequest
114
	Base() RequestorBaseRequest
115 116
}

Sietse Ringers's avatar
Sietse Ringers committed
117 118
// A ServiceProviderRequest contains a disclosure request.
type ServiceProviderRequest struct {
119
	RequestorBaseRequest
Sietse Ringers's avatar
Sietse Ringers committed
120 121 122 123 124
	Request *DisclosureRequest `json:"request"`
}

// A SignatureRequestorRequest contains a signing request.
type SignatureRequestorRequest struct {
125
	RequestorBaseRequest
Sietse Ringers's avatar
Sietse Ringers committed
126 127 128 129 130
	Request *SignatureRequest `json:"request"`
}

// An IdentityProviderRequest contains an issuance request.
type IdentityProviderRequest struct {
131
	RequestorBaseRequest
Sietse Ringers's avatar
Sietse Ringers committed
132 133 134 135 136 137
	Request *IssuanceRequest `json:"request"`
}

// ServiceProviderJwt is a requestor JWT for a disclosure session.
type ServiceProviderJwt struct {
	ServerJwt
138
	Request *ServiceProviderRequest `json:"sprequest"`
Sietse Ringers's avatar
Sietse Ringers committed
139 140 141 142 143
}

// SignatureRequestorJwt is a requestor JWT for a signing session.
type SignatureRequestorJwt struct {
	ServerJwt
144
	Request *SignatureRequestorRequest `json:"absrequest"`
Sietse Ringers's avatar
Sietse Ringers committed
145 146 147 148 149
}

// IdentityProviderJwt is a requestor JWT for issuance session.
type IdentityProviderJwt struct {
	ServerJwt
150 151 152
	Request *IdentityProviderRequest `json:"iprequest"`
}

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
// A RequestorJwt contains an IRMA session object.
type RequestorJwt interface {
	Action() Action
	RequestorRequest() RequestorRequest
	SessionRequest() SessionRequest
	Requestor() string
	Valid() error
	Sign(jwt.SigningMethod, interface{}) (string, error)
}

// A DisclosureChoice contains the attributes chosen to be disclosed.
type DisclosureChoice struct {
	Attributes [][]*AttributeIdentifier
}

// An AttributeRequest asks for an instance of an attribute type, possibly requiring it to have
// a specified value, in a session request.
type AttributeRequest struct {
171 172
	Type  AttributeTypeIdentifier `json:"type"`
	Value *string                 `json:"value"`
173 174 175 176 177 178 179 180 181 182
}

var (
	bigZero = big.NewInt(0)
	bigOne  = big.NewInt(1)
)

func (b *BaseRequest) GetContext() *big.Int {
	if b.Context == nil {
		return bigOne
183
	}
184
	return b.Context
185 186
}

187
func (b *BaseRequest) GetNonce(*atum.Timestamp) *big.Int {
188 189
	if b.Nonce == nil {
		return bigZero
190
	}
191
	return b.Nonce
192 193
}

194 195 196
// CredentialTypes returns an array of all credential types occuring in this conjunction.
func (c AttributeCon) CredentialTypes() []CredentialTypeIdentifier {
	var result []CredentialTypeIdentifier
197

198
	for _, attr := range c {
199 200 201 202
		typ := attr.Type.CredentialTypeIdentifier()
		if len(result) == 0 || result[len(result)-1] != typ {
			result = append(result, typ)
		}
203
	}
204

205
	return result
206 207
}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
func (c AttributeCon) Validate() error {
	// Unlike AttributeDisCon, we don't have to check here that the current instance is of length 0,
	// as that is actually a valid conjunction: one that specifies that the containing disjunction
	// is optional.

	credtypes := map[CredentialTypeIdentifier]struct{}{}
	var last CredentialTypeIdentifier
	for _, attr := range c {
		typ := attr.Type.CredentialTypeIdentifier()
		if _, contains := credtypes[typ]; contains && last != typ {
			return errors.New("Within inner conjunctions, attributes from the same credential type must be adjacent")
		}
		last = typ
		credtypes[typ] = struct{}{}
	}
	return nil
}

226 227
func (c *AttributeCon) MarshalJSON() ([]byte, error) {
	var vals bool
228
	l := make([]AttributeTypeIdentifier, 0, len(*c))
229 230 231 232 233 234

	for _, attr := range *c {
		if attr.Value == nil {
			l = append(l, attr.Type)
		} else {
			vals = true
235
			break
236 237 238 239
		}
	}

	if vals {
240
		return json.Marshal((*[]AttributeRequest)(c))
241 242 243
	} else {
		return json.Marshal(l)
	}
244 245
}

246 247
func (c *AttributeCon) UnmarshalJSON(bts []byte) error {
	var err error
248 249 250 251 252 253 254 255 256

	var l []AttributeTypeIdentifier
	if err = json.Unmarshal(bts, &l); err == nil {
		for _, id := range l {
			*c = append(*c, AttributeRequest{Type: id})
		}
		return nil
	}

257
	if err = json.Unmarshal(bts, (*[]AttributeRequest)(c)); err == nil {
258 259 260
		return nil
	}

261 262 263 264
	var s string
	if err = json.Unmarshal(bts, &s); err == nil {
		*c = append(*c, NewAttributeRequest(s))
		return nil
265 266
	}

267
	return errors.New("Failed to unmarshal attribute conjunction")
268 269
}

270 271
func (ar *AttributeRequest) Satisfy(attr AttributeTypeIdentifier, val *string) bool {
	return ar.Type == attr && (ar.Value == nil || (val != nil && *ar.Value == *val))
Sietse Ringers's avatar
Sietse Ringers committed
272 273
}

274
func (c AttributeCon) Satisfy(proofs gabi.ProofList, indices []*DisclosedAttributeIndex, conf *Configuration) (bool, []*DisclosedAttribute, error) {
275
	if len(indices) < len(c) {
276
		return false, nil, nil
277 278
	}
	attrs := make([]*DisclosedAttribute, 0, len(c))
279 280 281
	if len(c) == 0 {
		return true, attrs, nil
	}
282 283 284 285 286

	for j := range c {
		index := indices[j]
		attr, val, err := extractAttribute(proofs, index, conf)
		if err != nil {
287
			return false, nil, err
288 289
		}
		if !c[j].Satisfy(attr.Identifier, val) {
290
			return false, nil, nil
291 292 293
		}
		attrs = append(attrs, attr)
	}
294
	return true, attrs, nil
295 296
}

297 298 299 300 301 302 303 304 305 306 307 308 309
func (dc AttributeDisCon) Validate() error {
	if len(dc) == 0 {
		return errors.New("Empty disjunction")
	}
	var err error
	for _, con := range dc {
		if err = con.Validate(); err != nil {
			return err
		}
	}
	return nil
}

310
func (dc AttributeDisCon) Satisfy(proofs gabi.ProofList, indices []*DisclosedAttributeIndex, conf *Configuration) (bool, []*DisclosedAttribute, error) {
311
	for _, con := range dc {
312 313 314
		satisfied, attrs, err := con.Satisfy(proofs, indices, conf)
		if satisfied || err != nil {
			return true, attrs, err
315 316
		}
	}
317
	return false, nil, nil
318 319
}

320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
func (cdc AttributeConDisCon) Validate(conf *Configuration) error {
	for _, discon := range cdc {
		for _, con := range discon {
			var nonsingleton *CredentialTypeIdentifier
			for _, attr := range con {
				typ := attr.Type.CredentialTypeIdentifier()
				if !conf.CredentialTypes[typ].IsSingleton {
					if nonsingleton != nil && *nonsingleton != typ {
						return errors.New("Multiple non-singletons within one inner conjunction are not allowed")
					} else {
						nonsingleton = &typ
					}
				}
			}
		}
	}
	return nil
}

339 340 341 342 343 344 345 346
func (cdc AttributeConDisCon) Satisfy(disclosure *Disclosure, conf *Configuration) (bool, [][]*DisclosedAttribute, error) {
	if len(disclosure.Indices) < len(cdc) {
		return false, nil, nil
	}
	list := make([][]*DisclosedAttribute, len(cdc))
	complete := true

	for i, discon := range cdc {
347
		satisfied, attrs, err := discon.Satisfy(disclosure.Proofs, disclosure.Indices[i], conf)
348 349 350
		if err != nil {
			return false, nil, err
		}
351
		if satisfied {
352 353 354 355 356 357 358 359
			list[i] = attrs
		} else {
			complete = false
			list[i] = nil
		}
	}

	return complete, list, nil
360 361
}

362 363 364 365 366 367 368 369 370 371 372 373
func (cdc AttributeConDisCon) Iterate(f func(attr *AttributeRequest) error) error {
	var err error
	for _, discon := range cdc {
		for _, con := range discon {
			for _, attr := range con {
				if err = f(&attr); err != nil {
					return err
				}
			}
		}
	}
	return nil
374 375
}

376 377 378 379 380 381 382
func (dr *DisclosureRequest) AddSingle(attr AttributeTypeIdentifier, value *string, label TranslatedString) {
	dr.Disclose = append(dr.Disclose, AttributeDisCon{AttributeCon{{Type: attr, Value: value}}})
	dr.Labels[len(dr.Disclose)-1] = label
}

func NewDisclosureRequest(attrs ...AttributeTypeIdentifier) *DisclosureRequest {
	request := &DisclosureRequest{
383
		BaseRequest: BaseRequest{Type: ActionDisclosing, Version: 2},
384 385 386 387 388 389 390 391 392 393 394 395
		Labels:      map[int]TranslatedString{},
	}
	for _, attr := range attrs {
		request.AddSingle(attr, nil, nil)
	}
	return request
}

func NewSignatureRequest(message string, attrs ...AttributeTypeIdentifier) *SignatureRequest {
	dr := NewDisclosureRequest(attrs...)
	dr.Type = ActionSigning
	return &SignatureRequest{
396
		DisclosureRequest: *dr,
397 398 399 400 401 402 403 404
		Message:           message,
	}
}

func NewIssuanceRequest(creds []*CredentialRequest, attrs ...AttributeTypeIdentifier) *IssuanceRequest {
	dr := NewDisclosureRequest(attrs...)
	dr.Type = ActionIssuing
	return &IssuanceRequest{
405
		DisclosureRequest: *dr,
406 407 408 409 410 411 412 413 414
		Credentials:       creds,
	}
}

func (dr *DisclosureRequest) Disclosure() *DisclosureRequest {
	return dr
}

func (dr *DisclosureRequest) Identifiers() *IrmaIdentifierSet {
415 416
	if dr.ids == nil {
		dr.ids = &IrmaIdentifierSet{
417 418 419 420 421 422 423 424
			SchemeManagers:  map[SchemeManagerIdentifier]struct{}{},
			Issuers:         map[IssuerIdentifier]struct{}{},
			CredentialTypes: map[CredentialTypeIdentifier]struct{}{},
			PublicKeys:      map[IssuerIdentifier][]int{},
		}

		_ = dr.Disclose.Iterate(func(a *AttributeRequest) error {
			attr := a.Type
425 426 427
			dr.ids.SchemeManagers[attr.CredentialTypeIdentifier().IssuerIdentifier().SchemeManagerIdentifier()] = struct{}{}
			dr.ids.Issuers[attr.CredentialTypeIdentifier().IssuerIdentifier()] = struct{}{}
			dr.ids.CredentialTypes[attr.CredentialTypeIdentifier()] = struct{}{}
428 429 430
			return nil
		})
	}
431
	return dr.ids
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
}

func (dr *DisclosureRequest) Base() *BaseRequest {
	return &dr.BaseRequest
}

func (dr *DisclosureRequest) Action() Action { return ActionDisclosing }

func (dr *DisclosureRequest) Validate() error {
	if dr.Type != ActionDisclosing {
		return errors.New("Not a disclosure request")
	}
	if len(dr.Disclose) == 0 {
		return errors.New("Disclosure request had no attributes")
	}
447
	var err error
448
	for _, discon := range dr.Disclose {
449 450
		if err = discon.Validate(); err != nil {
			return err
451 452
		}
	}
453 454
	return nil
}
Sietse Ringers's avatar
Sietse Ringers committed
455

456 457
func (cr *CredentialRequest) Info(conf *Configuration, metadataVersion byte) (*CredentialInfo, error) {
	list, err := cr.AttributeList(conf, metadataVersion)
458 459 460
	if err != nil {
		return nil, err
	}
461
	return NewCredentialInfo(list.Ints, conf), nil
462 463
}

464 465 466 467
// Validate checks that this credential request is consistent with the specified Configuration:
// the credential type is known, all required attributes are present and no unknown attributes
// are given.
func (cr *CredentialRequest) Validate(conf *Configuration) error {
468
	credtype := conf.CredentialTypes[cr.CredentialTypeID]
Sietse Ringers's avatar
Sietse Ringers committed
469
	if credtype == nil {
470
		return errors.New("Credential request of unknown credential type")
Sietse Ringers's avatar
Sietse Ringers committed
471
	}
472 473 474 475 476

	// Check that there are no attributes in the credential request that aren't
	// in the credential descriptor.
	for crName := range cr.Attributes {
		found := false
477
		for _, ad := range credtype.AttributeTypes {
478 479 480 481 482 483
			if ad.ID == crName {
				found = true
				break
			}
		}
		if !found {
484
			return errors.New("Credential request contaiins unknown attribute")
485
		}
Sietse Ringers's avatar
Sietse Ringers committed
486 487
	}

488
	for _, attrtype := range credtype.AttributeTypes {
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
		if _, present := cr.Attributes[attrtype.ID]; !present && attrtype.Optional != "true" {
			return errors.New("Required attribute not present in credential request")
		}
	}

	return nil
}

// AttributeList returns the list of attributes from this credential request.
func (cr *CredentialRequest) AttributeList(conf *Configuration, metadataVersion byte) (*AttributeList, error) {
	if err := cr.Validate(conf); err != nil {
		return nil, err
	}

	// Compute metadata attribute
	meta := NewMetadataAttribute(metadataVersion)
	meta.setKeyCounter(cr.KeyCounter)
	meta.setCredentialTypeIdentifier(cr.CredentialTypeID.String())
	meta.setSigningDate()
	if err := meta.setExpiryDate(cr.Validity); err != nil {
		return nil, err
	}

	// Compute other attributes
513
	credtype := conf.CredentialTypes[cr.CredentialTypeID]
514
	attrs := make([]*big.Int, len(credtype.AttributeTypes)+1)
Sietse Ringers's avatar
Sietse Ringers committed
515
	attrs[0] = meta.Int
516
	for i, attrtype := range credtype.AttributeTypes {
517
		attrs[i+1] = new(big.Int)
Sietse Ringers's avatar
Sietse Ringers committed
518
		if str, present := cr.Attributes[attrtype.ID]; present {
519
			// Set attribute to str << 1 + 1
520
			attrs[i+1].SetBytes([]byte(str))
521 522 523 524
			if meta.Version() >= 0x03 {
				attrs[i+1].Lsh(attrs[i+1], 1)             // attr <<= 1
				attrs[i+1].Add(attrs[i+1], big.NewInt(1)) // attr += 1
			}
Sietse Ringers's avatar
Sietse Ringers committed
525 526 527
		}
	}

528
	return NewAttributeListFromInts(attrs, conf), nil
Sietse Ringers's avatar
Sietse Ringers committed
529 530
}

Sietse Ringers's avatar
Sietse Ringers committed
531
func (ir *IssuanceRequest) Identifiers() *IrmaIdentifierSet {
532 533
	if ir.ids == nil {
		ir.ids = &IrmaIdentifierSet{
534 535 536 537
			SchemeManagers:  map[SchemeManagerIdentifier]struct{}{},
			Issuers:         map[IssuerIdentifier]struct{}{},
			CredentialTypes: map[CredentialTypeIdentifier]struct{}{},
			PublicKeys:      map[IssuerIdentifier][]int{},
Sietse Ringers's avatar
Sietse Ringers committed
538 539
		}

Sietse Ringers's avatar
Sietse Ringers committed
540
		for _, credreq := range ir.Credentials {
Sietse Ringers's avatar
Sietse Ringers committed
541
			issuer := credreq.CredentialTypeID.IssuerIdentifier()
542 543 544 545 546
			ir.ids.SchemeManagers[issuer.SchemeManagerIdentifier()] = struct{}{}
			ir.ids.Issuers[issuer] = struct{}{}
			ir.ids.CredentialTypes[credreq.CredentialTypeID] = struct{}{}
			if ir.ids.PublicKeys[issuer] == nil {
				ir.ids.PublicKeys[issuer] = []int{}
547
			}
548
			ir.ids.PublicKeys[issuer] = append(ir.ids.PublicKeys[issuer], credreq.KeyCounter)
549 550
		}

551
		ir.ids.join(ir.DisclosureRequest.Identifiers())
Sietse Ringers's avatar
Sietse Ringers committed
552
	}
553
	return ir.ids
Sietse Ringers's avatar
Sietse Ringers committed
554 555
}

Tomas's avatar
Tomas committed
556 557 558 559 560 561 562 563 564 565 566 567 568
func (ir *IssuanceRequest) GetCredentialInfoList(conf *Configuration, version *ProtocolVersion) (CredentialInfoList, error) {
	if ir.CredentialInfoList == nil {
		for _, credreq := range ir.Credentials {
			info, err := credreq.Info(conf, GetMetadataVersion(version))
			if err != nil {
				return nil, err
			}
			ir.CredentialInfoList = append(ir.CredentialInfoList, info)
		}
	}
	return ir.CredentialInfoList, nil
}

569 570
func (ir *IssuanceRequest) Action() Action { return ActionIssuing }

571 572 573 574 575 576 577
func (ir *IssuanceRequest) Validate() error {
	if ir.Type != ActionIssuing {
		return errors.New("Not an issuance request")
	}
	if len(ir.Credentials) == 0 {
		return errors.New("Empty issuance request")
	}
578
	for _, cred := range ir.Credentials {
579
		if cred.Validity != nil && cred.Validity.Floor().Before(Timestamp(time.Now())) {
580 581 582
			return errors.New("Expired credential request")
		}
	}
583 584 585 586 587 588
	var err error
	for _, discon := range ir.Disclose {
		if err = discon.Validate(); err != nil {
			return err
		}
	}
589 590 591
	return nil
}

Sietse Ringers's avatar
Sietse Ringers committed
592 593
// GetNonce returns the nonce of this signature session
// (with the message already hashed into it).
594 595
func (sr *SignatureRequest) GetNonce(timestamp *atum.Timestamp) *big.Int {
	return ASN1ConvertSignatureNonce(sr.Message, sr.BaseRequest.GetNonce(nil), timestamp)
596 597
}

598
func (sr *SignatureRequest) SignatureFromMessage(message interface{}, timestamp *atum.Timestamp) (*SignedMessage, error) {
599
	signature, ok := message.(*Disclosure)
600 601 602 603 604

	if !ok {
		return nil, errors.Errorf("Type assertion failed")
	}

605 606 607 608
	nonce := sr.Nonce
	if nonce == nil {
		nonce = bigZero
	}
609
	return &SignedMessage{
610
		LDContext: SignedMessageLDContext,
611
		Signature: signature.Proofs,
612
		Indices:   signature.Indices,
613 614
		Nonce:     nonce,
		Context:   sr.GetContext(),
615
		Message:   sr.Message,
616
		Timestamp: timestamp,
617 618 619
	}, nil
}

620 621
func (sr *SignatureRequest) Action() Action { return ActionSigning }

622 623 624 625 626 627 628
func (sr *SignatureRequest) Validate() error {
	if sr.Type != ActionSigning {
		return errors.New("Not a signature request")
	}
	if sr.Message == "" {
		return errors.New("Signature request had empty message")
	}
629 630
	if len(sr.Disclose) == 0 {
		return errors.New("Signature request had no attributes")
631
	}
632
	var err error
633
	for _, discon := range sr.Disclose {
634 635
		if err = discon.Validate(); err != nil {
			return err
636 637
		}
	}
638 639 640
	return nil
}

641 642 643 644 645
// Check if Timestamp is before other Timestamp. Used for checking expiry of attributes
func (t Timestamp) Before(u Timestamp) bool {
	return time.Time(t).Before(time.Time(u))
}

646 647 648 649
func (t Timestamp) After(u Timestamp) bool {
	return time.Time(t).After(time.Time(u))
}

650 651
// MarshalJSON marshals a timestamp.
func (t *Timestamp) MarshalJSON() ([]byte, error) {
652
	return []byte(t.String()), nil
653 654 655 656 657 658 659 660 661 662 663
}

// UnmarshalJSON unmarshals a timestamp.
func (t *Timestamp) UnmarshalJSON(b []byte) error {
	ts, err := strconv.Atoi(string(b))
	if err != nil {
		return err
	}
	*t = Timestamp(time.Unix(int64(ts), 0))
	return nil
}
Sietse Ringers's avatar
Sietse Ringers committed
664

665 666 667 668 669
// Timestamp implements Stringer.
func (t *Timestamp) String() string {
	return fmt.Sprint(time.Time(*t).Unix())
}

670 671 672 673
func (t *Timestamp) Floor() Timestamp {
	return Timestamp(time.Unix((time.Time(*t).Unix()/ExpiryFactor)*ExpiryFactor, 0))
}

674 675 676 677 678 679 680 681
func readTimestamp(path string) (*Timestamp, bool, error) {
	exists, err := fs.PathExists(path)
	if err != nil {
		return nil, false, err
	}
	if !exists {
		return nil, false, nil
	}
682 683
	bts, err := ioutil.ReadFile(path)
	if err != nil {
684
		return nil, true, errors.New("Could not read scheme manager timestamp")
685
	}
686 687
	ts, err := parseTimestamp(bts)
	return ts, true, err
688 689
}

690
func parseTimestamp(bts []byte) (*Timestamp, error) {
691 692 693 694 695 696
	// Remove final character \n if present
	if bts[len(bts)-1] == '\n' {
		bts = bts[:len(bts)-1]
	}
	// convert from byte slice to string; parse as int
	str, err := strconv.ParseInt(string(bts), 10, 64)
697
	if err != nil {
698
		return nil, err
699
	}
700 701
	ts := Timestamp(time.Unix(str, 0))
	return &ts, nil
702 703
}

Sietse Ringers's avatar
Sietse Ringers committed
704 705 706 707 708 709 710 711
// NewServiceProviderJwt returns a new ServiceProviderJwt.
func NewServiceProviderJwt(servername string, dr *DisclosureRequest) *ServiceProviderJwt {
	return &ServiceProviderJwt{
		ServerJwt: ServerJwt{
			ServerName: servername,
			IssuedAt:   Timestamp(time.Now()),
			Type:       "verification_request",
		},
712 713 714 715
		Request: &ServiceProviderRequest{
			RequestorBaseRequest: RequestorBaseRequest{ResultJwtValidity: 120},
			Request:              dr,
		},
Sietse Ringers's avatar
Sietse Ringers committed
716 717 718 719 720 721 722 723 724 725 726
	}
}

// NewSignatureRequestorJwt returns a new SignatureRequestorJwt.
func NewSignatureRequestorJwt(servername string, sr *SignatureRequest) *SignatureRequestorJwt {
	return &SignatureRequestorJwt{
		ServerJwt: ServerJwt{
			ServerName: servername,
			IssuedAt:   Timestamp(time.Now()),
			Type:       "signature_request",
		},
727 728 729 730
		Request: &SignatureRequestorRequest{
			RequestorBaseRequest: RequestorBaseRequest{ResultJwtValidity: 120},
			Request:              sr,
		},
Sietse Ringers's avatar
Sietse Ringers committed
731 732 733 734 735 736 737 738 739 740 741
	}
}

// NewIdentityProviderJwt returns a new IdentityProviderJwt.
func NewIdentityProviderJwt(servername string, ir *IssuanceRequest) *IdentityProviderJwt {
	return &IdentityProviderJwt{
		ServerJwt: ServerJwt{
			ServerName: servername,
			IssuedAt:   Timestamp(time.Now()),
			Type:       "issue_request",
		},
742 743 744 745
		Request: &IdentityProviderRequest{
			RequestorBaseRequest: RequestorBaseRequest{ResultJwtValidity: 120},
			Request:              ir,
		},
Sietse Ringers's avatar
Sietse Ringers committed
746 747 748
	}
}

749 750 751 752 753 754 755
func (jwt *ServerJwt) Requestor() string { return jwt.ServerName }

func (r *ServiceProviderRequest) Validate() error {
	if r.Request == nil {
		return errors.New("Not a ServiceProviderRequest")
	}
	return r.Request.Validate()
Sietse Ringers's avatar
Sietse Ringers committed
756 757
}

758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
func (r *SignatureRequestorRequest) Validate() error {
	if r.Request == nil {
		return errors.New("Not a SignatureRequestorRequest")
	}
	return r.Request.Validate()
}

func (r *IdentityProviderRequest) Validate() error {
	if r.Request == nil {
		return errors.New("Not a IdentityProviderRequest")
	}
	return r.Request.Validate()
}

func (r *ServiceProviderRequest) SessionRequest() SessionRequest {
	return r.Request
}

func (r *SignatureRequestorRequest) SessionRequest() SessionRequest {
	return r.Request
}

func (r *IdentityProviderRequest) SessionRequest() SessionRequest {
	return r.Request
}

func (r *ServiceProviderRequest) Base() RequestorBaseRequest {
	return r.RequestorBaseRequest
}

func (r *SignatureRequestorRequest) Base() RequestorBaseRequest {
	return r.RequestorBaseRequest
}

func (r *IdentityProviderRequest) Base() RequestorBaseRequest {
	return r.RequestorBaseRequest
}
795

796
// SessionRequest returns an IRMA session object.
797
func (claims *ServiceProviderJwt) SessionRequest() SessionRequest { return claims.Request.Request }
Sietse Ringers's avatar
Sietse Ringers committed
798

799
// SessionRequest returns an IRMA session object.
800
func (claims *SignatureRequestorJwt) SessionRequest() SessionRequest { return claims.Request.Request }
Sietse Ringers's avatar
Sietse Ringers committed
801

802
// SessionRequest returns an IRMA session object.
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
func (claims *IdentityProviderJwt) SessionRequest() SessionRequest { return claims.Request.Request }

func (claims *ServiceProviderJwt) Sign(method jwt.SigningMethod, key interface{}) (string, error) {
	return jwt.NewWithClaims(method, claims).SignedString(key)
}

func (claims *SignatureRequestorJwt) Sign(method jwt.SigningMethod, key interface{}) (string, error) {
	return jwt.NewWithClaims(method, claims).SignedString(key)
}

func (claims *IdentityProviderJwt) Sign(method jwt.SigningMethod, key interface{}) (string, error) {
	return jwt.NewWithClaims(method, claims).SignedString(key)
}

func (claims *ServiceProviderJwt) RequestorRequest() RequestorRequest { return claims.Request }

func (claims *SignatureRequestorJwt) RequestorRequest() RequestorRequest { return claims.Request }

func (claims *IdentityProviderJwt) RequestorRequest() RequestorRequest { return claims.Request }

func (claims *ServiceProviderJwt) Valid() error {
	if claims.Type != "verification_request" {
825 826 827

		return errors.New("Verification jwt has invalid subject")
	}
828
	if time.Time(claims.IssuedAt).After(time.Now()) {
829 830 831 832 833
		return errors.New("Verification jwt not yet valid")
	}
	return nil
}

834 835
func (claims *SignatureRequestorJwt) Valid() error {
	if claims.Type != "signature_request" {
836 837
		return errors.New("Signature jwt has invalid subject")
	}
838
	if time.Time(claims.IssuedAt).After(time.Now()) {
839 840 841 842 843
		return errors.New("Signature jwt not yet valid")
	}
	return nil
}

844 845
func (claims *IdentityProviderJwt) Valid() error {
	if claims.Type != "issue_request" {
846 847
		return errors.New("Issuance jwt has invalid subject")
	}
848
	if time.Time(claims.IssuedAt).After(time.Now()) {
849 850 851 852 853
		return errors.New("Issuance jwt not yet valid")
	}
	return nil
}

854 855 856
func (claims *ServiceProviderJwt) Action() Action { return ActionDisclosing }

func (claims *SignatureRequestorJwt) Action() Action { return ActionSigning }
857

858
func (claims *IdentityProviderJwt) Action() Action { return ActionIssuing }
859

860
func SignSessionRequest(request SessionRequest, alg jwt.SigningMethod, key interface{}, name string) (string, error) {
861 862 863 864 865 866 867 868 869 870 871
	var jwtcontents RequestorJwt
	switch r := request.(type) {
	case *IssuanceRequest:
		jwtcontents = NewIdentityProviderJwt(name, r)
	case *DisclosureRequest:
		jwtcontents = NewServiceProviderJwt(name, r)
	case *SignatureRequest:
		jwtcontents = NewSignatureRequestorJwt(name, r)
	}
	return jwtcontents.Sign(alg, key)
}
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887

func SignRequestorRequest(request RequestorRequest, alg jwt.SigningMethod, key interface{}, name string) (string, error) {
	var jwtcontents RequestorJwt
	switch r := request.(type) {
	case *IdentityProviderRequest:
		jwtcontents = NewIdentityProviderJwt(name, nil)
		jwtcontents.(*IdentityProviderJwt).Request = r
	case *ServiceProviderRequest:
		jwtcontents = NewServiceProviderJwt(name, nil)
		jwtcontents.(*ServiceProviderJwt).Request = r
	case *SignatureRequestorRequest:
		jwtcontents = NewSignatureRequestorJwt(name, nil)
		jwtcontents.(*SignatureRequestorJwt).Request = r
	}
	return jwtcontents.Sign(alg, key)
}
888 889 890 891 892

// NewAttributeRequest requests the specified attribute.
func NewAttributeRequest(attr string) AttributeRequest {
	return AttributeRequest{Type: NewAttributeTypeIdentifier(attr)}
}