Commit 9f8041f8 authored by Sietse Ringers's avatar Sietse Ringers
Browse files

Cleanup, comments, better names, make consistent

parent eafa8900
......@@ -3,12 +3,11 @@ package irmago
import (
"crypto/sha256"
"encoding/binary"
"encoding/json"
"errors"
"math/big"
"time"
"encoding/json"
"github.com/mhe/gabi"
)
......
......@@ -224,7 +224,7 @@ func (cm *CredentialManager) Candidates(disjunction *AttributeDisjunction) []*At
} else {
attrs := NewAttributeListFromInts(cred.Attributes[1:])
val := attrs.Attribute(attribute)
if val == "" {
if val == "" { // This won't handle empty attributes correctly
continue
}
if !disjunction.HasValues() || val == disjunction.Values[attribute] {
......@@ -279,12 +279,12 @@ func (cm *CredentialManager) groupCredentials(choice *DisclosureChoice) (map[Cre
return grouped, nil
}
type sessionRequest interface {
type Session interface {
GetNonce() *big.Int
GetContext() *big.Int
}
func (cm *CredentialManager) proofsBuilders(choice *DisclosureChoice, request sessionRequest) ([]gabi.ProofBuilder, error) {
func (cm *CredentialManager) proofsBuilders(choice *DisclosureChoice) ([]gabi.ProofBuilder, error) {
todisclose, err := cm.groupCredentials(choice)
if err != nil {
return nil, err
......@@ -301,12 +301,12 @@ func (cm *CredentialManager) proofsBuilders(choice *DisclosureChoice, request se
return builders, nil
}
func (cm *CredentialManager) Proofs(choice *DisclosureChoice, request sessionRequest, issig bool) (gabi.ProofList, error) {
builders, err := cm.proofsBuilders(choice, request)
func (cm *CredentialManager) Proofs(choice *DisclosureChoice, request Session, issig bool) (gabi.ProofList, error) {
builders, err := cm.proofsBuilders(choice)
if err != nil {
return nil, err
}
return gabi.BuildProofList(request.GetContext(), request.GetNonce(), builders, false), nil
return gabi.BuildProofList(request.GetContext(), request.GetNonce(), builders, issig), nil
}
func (cm *CredentialManager) IssueCommitments(choice *DisclosureChoice, request *IssuanceRequest) (*gabi.IssueCommitmentMessage, error) {
......@@ -324,7 +324,7 @@ func (cm *CredentialManager) IssueCommitments(choice *DisclosureChoice, request
proofBuilders = append(proofBuilders, credBuilder)
}
disclosures, err := cm.proofsBuilders(choice, request)
disclosures, err := cm.proofsBuilders(choice)
if err != nil {
return nil, err
}
......@@ -339,6 +339,8 @@ func (cm *CredentialManager) ConstructCredentials(msg []*gabi.IssueSignatureMess
return errors.New("Received unexpected amount of signatures")
}
// First collect all credentials in a slice, so that if one of them induces an error,
// we save none of them to fail the session cleanly
creds := []*gabi.Credential{}
for i, sig := range msg {
attrs, err := request.Credentials[i].AttributeList()
......@@ -353,7 +355,7 @@ func (cm *CredentialManager) ConstructCredentials(msg []*gabi.IssueSignatureMess
}
for _, cred := range creds {
cm.addCredential(newCredential(cred))
cm.Add(newCredential(cred))
}
return nil
......
......@@ -2,6 +2,7 @@ package protocol
import (
"encoding/json"
"errors"
"fmt"
"math/big"
......@@ -79,9 +80,8 @@ type SessionInfo struct {
func (e *Error) Error() string {
if e.error != nil {
return fmt.Sprintf("%s: %s", string(e.ErrorCode), e.error.Error())
} else {
return string(e.ErrorCode)
}
return string(e.ErrorCode)
}
/*
......@@ -115,9 +115,21 @@ func (si *SessionInfo) UnmarshalJSON(b []byte) error {
si.Context = temp.Context
si.Keys = make(map[irmago.IssuerIdentifier]int, len(temp.Keys))
for _, item := range temp.Keys {
idmap := item[0].(map[string]interface{})
id := irmago.NewIssuerIdentifier(idmap["identifier"].(string))
si.Keys[id] = int(item[1].(float64))
var idmap map[string]interface{}
var idstr string
var counter float64
var ok bool
if idmap, ok = item[0].(map[string]interface{}); !ok {
return errors.New("Failed to deserialize session info")
}
if idstr, ok = idmap["identifier"].(string); !ok {
return errors.New("Failed to deserialize session info")
}
if counter, ok = item[1].(float64); !ok {
return errors.New("Failed to deserialize session info")
}
id := irmago.NewIssuerIdentifier(idstr)
si.Keys[id] = int(counter)
}
return nil
}
......@@ -7,21 +7,21 @@ import (
)
type ServerJwt struct {
ServerName string `json:"iss"`
IssuedAt *irmago.Timestamp `json:"iat"`
Type string `json:"sub"`
Type string `json:"sub"`
ServerName string `json:"iss"`
IssuedAt irmago.Timestamp `json:"iat"`
}
type ServiceProviderRequest struct {
Request irmago.DisclosureRequest `json:"request"`
Request *irmago.DisclosureRequest `json:"request"`
}
type SignatureServerRequest struct {
Request irmago.SignatureRequest `json:"request"`
Request *irmago.SignatureRequest `json:"request"`
}
type IdentityProviderRequest struct {
Request irmago.IssuanceRequest `json:"request"`
Request *irmago.IssuanceRequest `json:"request"`
}
type ServiceProviderJwt struct {
......@@ -39,36 +39,33 @@ type IdentityProviderJwt struct {
Request IdentityProviderRequest `json:"iprequest"`
}
func NewServiceProviderJwt(servername string, dr irmago.DisclosureRequest) *ServiceProviderJwt {
now := irmago.Timestamp(time.Now())
func NewServiceProviderJwt(servername string, dr *irmago.DisclosureRequest) *ServiceProviderJwt {
return &ServiceProviderJwt{
ServerJwt: ServerJwt{
ServerName: servername,
IssuedAt: &now,
IssuedAt: irmago.Timestamp(time.Now()),
Type: "verification_request",
},
Request: ServiceProviderRequest{Request: dr},
}
}
func NewSignatureServerJwt(servername string, sr irmago.SignatureRequest) *SignatureServerJwt {
now := irmago.Timestamp(time.Now())
func NewSignatureServerJwt(servername string, sr *irmago.SignatureRequest) *SignatureServerJwt {
return &SignatureServerJwt{
ServerJwt: ServerJwt{
ServerName: servername,
IssuedAt: &now,
IssuedAt: irmago.Timestamp(time.Now()),
Type: "signature_request",
},
Request: SignatureServerRequest{Request: sr},
}
}
func NewIdentityProviderJwt(servername string, ir irmago.IssuanceRequest) *IdentityProviderJwt {
now := irmago.Timestamp(time.Now())
func NewIdentityProviderJwt(servername string, ir *irmago.IssuanceRequest) *IdentityProviderJwt {
return &IdentityProviderJwt{
ServerJwt: ServerJwt{
ServerName: servername,
IssuedAt: &now,
IssuedAt: irmago.Timestamp(time.Now()),
Type: "issue_request",
},
Request: IdentityProviderRequest{Request: ir},
......
......@@ -56,17 +56,24 @@ var supportedVersions = map[int][]int{
func calcVersion(qr *Qr) (string, error) {
// Parse range supported by server
minmajor, err := strconv.Atoi(string(qr.ProtocolVersion[0]))
minminor, err := strconv.Atoi(string(qr.ProtocolVersion[2]))
maxmajor, err := strconv.Atoi(string(qr.ProtocolMaxVersion[0]))
maxminor, err := strconv.Atoi(string(qr.ProtocolMaxVersion[2]))
if err != nil {
var minmajor, minminor, maxmajor, maxminor int
var err error
if minmajor, err = strconv.Atoi(string(qr.ProtocolVersion[0])); err != nil {
return "", err
}
if minminor, err = strconv.Atoi(string(qr.ProtocolVersion[2])); err != nil {
return "", err
}
if maxmajor, err = strconv.Atoi(string(qr.ProtocolMaxVersion[0])); err != nil {
return "", err
}
if maxminor, err = strconv.Atoi(string(qr.ProtocolMaxVersion[2])); err != nil {
return "", err
}
// Iterate supportedVersions in reverse sorted order (i.e. biggest major number first)
keys := make([]int, 0, len(supportedVersions))
for k, _ := range supportedVersions {
for k := range supportedVersions {
keys = append(keys, k)
}
sort.Sort(sort.Reverse(sort.IntSlice(keys)))
......@@ -141,9 +148,13 @@ func (session *Session) start() {
}
headerbytes, err := base64.RawStdEncoding.DecodeString(jwtparts[0])
if err != nil {
session.Handler.Failure(session.Action, &Error{ErrorCode: ErrorInvalidJWT, error: err})
return
}
bodybytes, err := base64.RawStdEncoding.DecodeString(jwtparts[1])
if err != nil {
session.Handler.Failure(session.Action, &Error{ErrorCode: ErrorInvalidJWT})
session.Handler.Failure(session.Action, &Error{ErrorCode: ErrorInvalidJWT, error: err})
return
}
......@@ -152,7 +163,7 @@ func (session *Session) start() {
}
err = json.Unmarshal([]byte(headerbytes), &header)
if err != nil {
session.Handler.Failure(session.Action, &Error{ErrorCode: ErrorInvalidJWT})
session.Handler.Failure(session.Action, &Error{ErrorCode: ErrorInvalidJWT, error: err})
return
}
......@@ -179,7 +190,7 @@ func (session *Session) start() {
panic("Invalid session type") // does not happen, session.Action has been checked earlier
}
if err != nil {
session.Handler.Failure(session.Action, &Error{ErrorCode: ErrorInvalidJWT})
session.Handler.Failure(session.Action, &Error{ErrorCode: ErrorInvalidJWT, error: err})
return
}
......@@ -203,11 +214,11 @@ func (session *Session) start() {
session.Handler.StatusUpdate(session.Action, StatusConnected)
switch session.Action {
case ActionDisclosing:
session.Handler.AskVerificationPermission(session.spRequest.Request.Request, header.Server, callback)
session.Handler.AskVerificationPermission(*session.spRequest.Request.Request, header.Server, callback)
case ActionSigning:
session.Handler.AskSignaturePermission(session.ssRequest.Request.Request, header.Server, callback)
session.Handler.AskSignaturePermission(*session.ssRequest.Request.Request, header.Server, callback)
case ActionIssuing:
session.Handler.AskIssuancePermission(session.ipRequest.Request.Request, header.Server, callback)
session.Handler.AskIssuancePermission(*session.ipRequest.Request.Request, header.Server, callback)
default:
panic("Invalid session type") // does not happen, session.Action has been checked earlier
}
......@@ -224,11 +235,11 @@ func (session *Session) do(proceed bool, choice *irmago.DisclosureChoice) {
var err error
switch session.Action {
case ActionSigning:
message, err = irmago.Manager.Proofs(choice, &session.ssRequest.Request.Request, true)
message, err = irmago.Manager.Proofs(choice, session.ssRequest.Request.Request, true)
case ActionDisclosing:
message, err = irmago.Manager.Proofs(choice, &session.spRequest.Request.Request, false)
message, err = irmago.Manager.Proofs(choice, session.spRequest.Request.Request, false)
case ActionIssuing:
message, err = irmago.Manager.IssueCommitments(choice, &session.ipRequest.Request.Request)
message, err = irmago.Manager.IssueCommitments(choice, session.ipRequest.Request.Request)
}
if err != nil {
session.Handler.Failure(session.Action, &Error{ErrorCode: ErrorCrypto, error: err})
......@@ -243,7 +254,7 @@ func (session *Session) do(proceed bool, choice *irmago.DisclosureChoice) {
err = session.transport.Post("proofs", &response, message)
if err != nil {
session.Handler.Failure(session.Action,
&Error{ErrorCode: ErrorTransport, ApiError: err.(*TransportError).ApiErr, info: err.Error()})
&Error{ErrorCode: ErrorTransport, ApiError: err.(*TransportError).ApiErr, info: err.Error(), error: err})
return
}
if response != "VALID" {
......@@ -255,11 +266,11 @@ func (session *Session) do(proceed bool, choice *irmago.DisclosureChoice) {
err = session.transport.Post("commitments", &response, message)
if err != nil {
session.Handler.Failure(session.Action,
&Error{ErrorCode: ErrorTransport, ApiError: err.(*TransportError).ApiErr, info: err.Error()})
&Error{ErrorCode: ErrorTransport, ApiError: err.(*TransportError).ApiErr, info: err.Error(), error: err})
return
}
err = irmago.Manager.ConstructCredentials(response, &session.ipRequest.Request.Request)
err = irmago.Manager.ConstructCredentials(response, session.ipRequest.Request.Request)
if err != nil {
session.Handler.Failure(session.Action, &Error{ErrorCode: ErrorCrypto, error: err})
return
......
......@@ -90,7 +90,7 @@ func (th TestHandler) AskSignaturePermission(request irmago.SignatureRequest, Se
}
func getDisclosureJwt(name string, id irmago.AttributeTypeIdentifier) interface{} {
return NewServiceProviderJwt(name, irmago.DisclosureRequest{
return NewServiceProviderJwt(name, &irmago.DisclosureRequest{
Content: irmago.AttributeDisjunctionList([]*irmago.AttributeDisjunction{
&irmago.AttributeDisjunction{
Label: "foo",
......@@ -101,7 +101,7 @@ func getDisclosureJwt(name string, id irmago.AttributeTypeIdentifier) interface{
}
func getSigningJwt(name string, id irmago.AttributeTypeIdentifier) interface{} {
return NewSignatureServerJwt(name, irmago.SignatureRequest{
return NewSignatureServerJwt(name, &irmago.SignatureRequest{
Message: "test",
MessageType: "STRING",
DisclosureRequest: irmago.DisclosureRequest{
......@@ -119,7 +119,7 @@ func getIssuanceJwt(name string, id irmago.AttributeTypeIdentifier) interface{}
expiry := irmago.Timestamp(irmago.NewMetadataAttribute().Expiry())
credid1 := irmago.NewCredentialTypeIdentifier("irma-demo.RU.studentCard")
credid2 := irmago.NewCredentialTypeIdentifier("irma-demo.MijnOverheid.root")
return NewIdentityProviderJwt(name, irmago.IssuanceRequest{
return NewIdentityProviderJwt(name, &irmago.IssuanceRequest{
Credentials: []*irmago.CredentialRequest{
&irmago.CredentialRequest{
Validity: &expiry,
......@@ -174,8 +174,8 @@ func sessionHelper(t *testing.T, jwtcontents interface{}, url string) {
parseStorage(t)
parseAndroidStorage(t)
//url = "http://localhost:8081/irma_api_server/api/v2/" + url
url = "https://demo.irmacard.org/tomcat/irma_api_server/api/v2/" + url
url = "http://localhost:8081/irma_api_server/api/v2/" + url
//url = "https://demo.irmacard.org/tomcat/irma_api_server/api/v2/" + url
headerbytes, err := json.Marshal(&map[string]string{"alg": "none", "typ": "JWT"})
require.NoError(t, err)
......
......@@ -3,7 +3,6 @@ package protocol
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
......@@ -66,7 +65,7 @@ func (transport *HTTPTransport) request(url string, method string, result interf
if err != nil {
return &TransportError{Err: err.Error()}
}
fmt.Printf("POST: %s\n", string(marshaled))
//fmt.Printf("POST: %s\n", string(marshaled))
reader = bytes.NewBuffer(marshaled)
}
}
......@@ -100,11 +99,11 @@ func (transport *HTTPTransport) request(url string, method string, result interf
if apierr.ErrorName == "" { // Not an ApiErrorMessage
return &TransportError{Status: res.StatusCode}
}
fmt.Printf("ERROR: %+v\n", apierr)
//fmt.Printf("ERROR: %+v\n", apierr)
return &TransportError{Err: apierr.ErrorName, Status: res.StatusCode, ApiErr: apierr}
}
fmt.Printf("RESPONSE: %s\n", string(body))
//fmt.Printf("RESPONSE: %s\n", string(body))
err = json.Unmarshal(body, result)
if err != nil {
return &TransportError{Err: err.Error(), Status: res.StatusCode}
......
......@@ -135,6 +135,9 @@ func (cm *CredentialManager) loadSignature(id CredentialTypeIdentifier, counter
return
}
bytes, err := ioutil.ReadFile(path)
if err != nil {
return
}
signature = new(gabi.CLSignature)
err = json.Unmarshal(bytes, signature)
return
......@@ -148,11 +151,11 @@ func (cm *CredentialManager) loadSecretKey() (*big.Int, error) {
return nil, err
}
if exists {
bytes, err := ioutil.ReadFile(cm.path(skFile))
if err != nil {
return nil, err
var bytes []byte
if bytes, err = ioutil.ReadFile(cm.path(skFile)); err == nil {
return new(big.Int).SetBytes(bytes), nil
}
return new(big.Int).SetBytes(bytes), nil
return nil, err
}
sk, err := cm.generateSecretKey()
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment