...

Source file src/github.com/letsencrypt/boulder/mocks/mocks.go

Documentation: github.com/letsencrypt/boulder/mocks

     1  package mocks
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"crypto/x509"
     7  	"encoding/pem"
     8  	"errors"
     9  	"fmt"
    10  	"math/rand"
    11  	"net"
    12  	"os"
    13  	"sync"
    14  	"time"
    15  
    16  	"github.com/jmhodges/clock"
    17  	"google.golang.org/grpc"
    18  	"google.golang.org/grpc/codes"
    19  	"google.golang.org/grpc/status"
    20  	"google.golang.org/protobuf/types/known/emptypb"
    21  	"google.golang.org/protobuf/types/known/timestamppb"
    22  	"gopkg.in/go-jose/go-jose.v2"
    23  
    24  	"github.com/letsencrypt/boulder/core"
    25  	corepb "github.com/letsencrypt/boulder/core/proto"
    26  	berrors "github.com/letsencrypt/boulder/errors"
    27  	bgrpc "github.com/letsencrypt/boulder/grpc"
    28  	"github.com/letsencrypt/boulder/identifier"
    29  	"github.com/letsencrypt/boulder/mail"
    30  	pubpb "github.com/letsencrypt/boulder/publisher/proto"
    31  	sapb "github.com/letsencrypt/boulder/sa/proto"
    32  )
    33  
    34  // StorageAuthorityReadOnly is a mock of sapb.StorageAuthorityReadOnlyClient
    35  type StorageAuthorityReadOnly struct {
    36  	clk clock.Clock
    37  }
    38  
    39  // NewStorageAuthorityReadOnly creates a new mock read-only storage authority
    40  // with the given clock.
    41  func NewStorageAuthorityReadOnly(clk clock.Clock) *StorageAuthorityReadOnly {
    42  	return &StorageAuthorityReadOnly{clk}
    43  }
    44  
    45  // StorageAuthority is a mock of sapb.StorageAuthorityClient
    46  type StorageAuthority struct {
    47  	StorageAuthorityReadOnly
    48  }
    49  
    50  // NewStorageAuthority creates a new mock storage authority
    51  // with the given clock.
    52  func NewStorageAuthority(clk clock.Clock) *StorageAuthority {
    53  	return &StorageAuthority{StorageAuthorityReadOnly{clk}}
    54  }
    55  
    56  const (
    57  	test1KeyPublicJSON  = `{"kty":"RSA","n":"yNWVhtYEKJR21y9xsHV-PD_bYwbXSeNuFal46xYxVfRL5mqha7vttvjB_vc7Xg2RvgCxHPCqoxgMPTzHrZT75LjCwIW2K_klBYN8oYvTwwmeSkAz6ut7ZxPv-nZaT5TJhGk0NT2kh_zSpdriEJ_3vW-mqxYbbBmpvHqsa1_zx9fSuHYctAZJWzxzUZXykbWMWQZpEiE0J4ajj51fInEzVn7VxV-mzfMyboQjujPh7aNJxAWSq4oQEJJDgWwSh9leyoJoPpONHxh5nEE5AjE01FkGICSxjpZsF-w8hOTI3XXohUdu29Se26k2B0PolDSuj0GIQU6-W9TdLXSjBb2SpQ","e":"AQAB"}`
    58  	test2KeyPublicJSON  = `{"kty":"RSA","n":"qnARLrT7Xz4gRcKyLdydmCr-ey9OuPImX4X40thk3on26FkMznR3fRjs66eLK7mmPcBZ6uOJseURU6wAaZNmemoYx1dMvqvWWIyiQleHSD7Q8vBrhR6uIoO4jAzJZR-ChzZuSDt7iHN-3xUVspu5XGwXU_MVJZshTwp4TaFx5elHIT_ObnTvTOU3Xhish07AbgZKmWsVbXh5s-CrIicU4OexJPgunWZ_YJJueOKmTvnLlTV4MzKR2oZlBKZ27S0-SfdV_QDx_ydle5oMAyKVtlAV35cyPMIsYNwgUGBCdY_2Uzi5eX0lTc7MPRwz6qR1kip-i59VcGcUQgqHV6Fyqw","e":"AQAB"}`
    59  	testE1KeyPublicJSON = `{"kty":"EC","crv":"P-256","x":"FwvSZpu06i3frSk_mz9HcD9nETn4wf3mQ-zDtG21Gao","y":"S8rR-0dWa8nAcw1fbunF_ajS3PQZ-QwLps-2adgLgPk"}`
    60  	testE2KeyPublicJSON = `{"kty":"EC","crv":"P-256","x":"S8FOmrZ3ywj4yyFqt0etAD90U-EnkNaOBSLfQmf7pNg","y":"vMvpDyqFDRHjGfZ1siDOm5LS6xNdR5xTpyoQGLDOX2Q"}`
    61  	test3KeyPublicJSON  = `{"kty":"RSA","n":"uTQER6vUA1RDixS8xsfCRiKUNGRzzyIK0MhbS2biClShbb0hSx2mPP7gBvis2lizZ9r-y9hL57kNQoYCKndOBg0FYsHzrQ3O9AcoV1z2Mq-XhHZbFrVYaXI0M3oY9BJCWog0dyi3XC0x8AxC1npd1U61cToHx-3uSvgZOuQA5ffEn5L38Dz1Ti7OV3E4XahnRJvejadUmTkki7phLBUXm5MnnyFm0CPpf6ApV7zhLjN5W-nV0WL17o7v8aDgV_t9nIdi1Y26c3PlCEtiVHZcebDH5F1Deta3oLLg9-g6rWnTqPbY3knffhp4m0scLD6e33k8MtzxDX_D7vHsg0_X1w","e":"AQAB"}`
    62  	test4KeyPublicJSON  = `{"kty":"RSA","n":"qih-cx32M0wq8MhhN-kBi2xPE-wnw4_iIg1hWO5wtBfpt2PtWikgPuBT6jvK9oyQwAWbSfwqlVZatMPY_-3IyytMNb9R9OatNr6o5HROBoyZnDVSiC4iMRd7bRl_PWSIqj_MjhPNa9cYwBdW5iC3jM5TaOgmp0-YFm4tkLGirDcIBDkQYlnv9NKILvuwqkapZ7XBixeqdCcikUcTRXW5unqygO6bnapzw-YtPsPPlj4Ih3SvK4doyziPV96U8u5lbNYYEzYiW1mbu9n0KLvmKDikGcdOpf6-yRa_10kMZyYQatY1eclIKI0xb54kbluEl0GQDaL5FxLmiKeVnsapzw","e":"AQAB"}`
    63  
    64  	agreementURL = "http://example.invalid/terms"
    65  )
    66  
    67  // GetRegistration is a mock
    68  func (sa *StorageAuthorityReadOnly) GetRegistration(_ context.Context, req *sapb.RegistrationID, _ ...grpc.CallOption) (*corepb.Registration, error) {
    69  	if req.Id == 100 {
    70  		// Tag meaning "Missing"
    71  		return nil, errors.New("missing")
    72  	}
    73  	if req.Id == 101 {
    74  		// Tag meaning "Malformed"
    75  		return &corepb.Registration{}, nil
    76  	}
    77  	if req.Id == 102 {
    78  		// Tag meaning "Not Found"
    79  		return nil, berrors.NotFoundError("Dave's not here man")
    80  	}
    81  
    82  	goodReg := &corepb.Registration{
    83  		Id:              req.Id,
    84  		Key:             []byte(test1KeyPublicJSON),
    85  		Agreement:       agreementURL,
    86  		Contact:         []string{"mailto:person@mail.com"},
    87  		ContactsPresent: true,
    88  		Status:          string(core.StatusValid),
    89  	}
    90  
    91  	// Return a populated registration with contacts for ID == 1 or ID == 5
    92  	if req.Id == 1 || req.Id == 5 {
    93  		return goodReg, nil
    94  	}
    95  
    96  	// Return a populated registration with a different key for ID == 2
    97  	if req.Id == 2 {
    98  		goodReg.Key = []byte(test2KeyPublicJSON)
    99  		return goodReg, nil
   100  	}
   101  
   102  	// Return a deactivated registration with a different key for ID == 3
   103  	if req.Id == 3 {
   104  		goodReg.Key = []byte(test3KeyPublicJSON)
   105  		goodReg.Status = string(core.StatusDeactivated)
   106  		return goodReg, nil
   107  	}
   108  
   109  	// Return a populated registration with a different key for ID == 4
   110  	if req.Id == 4 {
   111  		goodReg.Key = []byte(test4KeyPublicJSON)
   112  		return goodReg, nil
   113  	}
   114  
   115  	// Return a registration without the agreement set for ID == 6
   116  	if req.Id == 6 {
   117  		goodReg.Agreement = ""
   118  		return goodReg, nil
   119  	}
   120  
   121  	goodReg.InitialIP, _ = net.ParseIP("5.6.7.8").MarshalText()
   122  	createdAt := time.Date(2003, 9, 27, 0, 0, 0, 0, time.UTC)
   123  	goodReg.CreatedAtNS = createdAt.UnixNano()
   124  	return goodReg, nil
   125  }
   126  
   127  // GetRegistrationByKey is a mock
   128  func (sa *StorageAuthorityReadOnly) GetRegistrationByKey(_ context.Context, req *sapb.JSONWebKey, _ ...grpc.CallOption) (*corepb.Registration, error) {
   129  	test5KeyBytes, err := os.ReadFile("../test/test-key-5.der")
   130  	if err != nil {
   131  		return nil, err
   132  	}
   133  	test5KeyPriv, err := x509.ParsePKCS1PrivateKey(test5KeyBytes)
   134  	if err != nil {
   135  		return nil, err
   136  	}
   137  	test5KeyPublic := jose.JSONWebKey{Key: test5KeyPriv.Public()}
   138  	test5KeyPublicJSON, err := test5KeyPublic.MarshalJSON()
   139  	if err != nil {
   140  		return nil, err
   141  	}
   142  
   143  	contacts := []string{"mailto:person@mail.com"}
   144  
   145  	if bytes.Equal(req.Jwk, []byte(test1KeyPublicJSON)) {
   146  		return &corepb.Registration{
   147  			Id:              1,
   148  			Key:             req.Jwk,
   149  			Agreement:       agreementURL,
   150  			Contact:         contacts,
   151  			ContactsPresent: true,
   152  			Status:          string(core.StatusValid),
   153  		}, nil
   154  	}
   155  
   156  	if bytes.Equal(req.Jwk, []byte(test2KeyPublicJSON)) {
   157  		// No key found
   158  		return &corepb.Registration{Id: 2}, berrors.NotFoundError("reg not found")
   159  	}
   160  
   161  	if bytes.Equal(req.Jwk, []byte(test4KeyPublicJSON)) {
   162  		// No key found
   163  		return &corepb.Registration{Id: 5}, berrors.NotFoundError("reg not found")
   164  	}
   165  
   166  	if bytes.Equal(req.Jwk, test5KeyPublicJSON) {
   167  		// No key found
   168  		return &corepb.Registration{Id: 5}, berrors.NotFoundError("reg not found")
   169  	}
   170  
   171  	if bytes.Equal(req.Jwk, []byte(testE1KeyPublicJSON)) {
   172  		return &corepb.Registration{Id: 3, Key: req.Jwk, Agreement: agreementURL}, nil
   173  	}
   174  
   175  	if bytes.Equal(req.Jwk, []byte(testE2KeyPublicJSON)) {
   176  		return &corepb.Registration{Id: 4}, berrors.NotFoundError("reg not found")
   177  	}
   178  
   179  	if bytes.Equal(req.Jwk, []byte(test3KeyPublicJSON)) {
   180  		// deactivated registration
   181  		return &corepb.Registration{
   182  			Id:              2,
   183  			Key:             req.Jwk,
   184  			Agreement:       agreementURL,
   185  			Contact:         contacts,
   186  			ContactsPresent: true,
   187  			Status:          string(core.StatusDeactivated),
   188  		}, nil
   189  	}
   190  
   191  	// Return a fake registration. Make sure to fill the key field to avoid marshaling errors.
   192  	return &corepb.Registration{
   193  		Id:        1,
   194  		Key:       []byte(test1KeyPublicJSON),
   195  		Agreement: agreementURL,
   196  		Status:    string(core.StatusValid),
   197  	}, nil
   198  }
   199  
   200  // GetSerialMetadata is a mock
   201  func (sa *StorageAuthorityReadOnly) GetSerialMetadata(ctx context.Context, req *sapb.Serial, _ ...grpc.CallOption) (*sapb.SerialMetadata, error) {
   202  	now := sa.clk.Now()
   203  	created := now.Add(-1 * time.Hour)
   204  	expires := now.Add(2159 * time.Hour)
   205  	return &sapb.SerialMetadata{
   206  		Serial:         req.Serial,
   207  		RegistrationID: 1,
   208  		CreatedNS:      created.UnixNano(),
   209  		Created:        timestamppb.New(created),
   210  		ExpiresNS:      expires.UnixNano(),
   211  		Expires:        timestamppb.New(expires),
   212  	}, nil
   213  }
   214  
   215  // GetCertificate is a mock
   216  func (sa *StorageAuthorityReadOnly) GetCertificate(_ context.Context, req *sapb.Serial, _ ...grpc.CallOption) (*corepb.Certificate, error) {
   217  	issuedTime := sa.clk.Now().Add(-1 * time.Hour)
   218  
   219  	// Serial ee == 238.crt
   220  	if req.Serial == "0000000000000000000000000000000000ee" {
   221  		certPemBytes, _ := os.ReadFile("test/238.crt")
   222  		certBlock, _ := pem.Decode(certPemBytes)
   223  		return &corepb.Certificate{
   224  			RegistrationID: 1,
   225  			Der:            certBlock.Bytes,
   226  			IssuedNS:       issuedTime.UnixNano(),
   227  			Issued:         timestamppb.New(issuedTime),
   228  		}, nil
   229  	} else if req.Serial == "0000000000000000000000000000000000b2" {
   230  		certPemBytes, _ := os.ReadFile("test/178.crt")
   231  		certBlock, _ := pem.Decode(certPemBytes)
   232  		return &corepb.Certificate{
   233  			RegistrationID: 1,
   234  			Der:            certBlock.Bytes,
   235  			IssuedNS:       issuedTime.UnixNano(),
   236  			Issued:         timestamppb.New(issuedTime),
   237  		}, nil
   238  	} else if req.Serial == "000000000000000000000000000000626164" {
   239  		return nil, errors.New("bad")
   240  	} else {
   241  		return nil, berrors.NotFoundError("No cert")
   242  	}
   243  }
   244  
   245  // GetCertificateStatus is a mock
   246  func (sa *StorageAuthorityReadOnly) GetCertificateStatus(_ context.Context, req *sapb.Serial, _ ...grpc.CallOption) (*corepb.CertificateStatus, error) {
   247  	// Serial ee == 238.crt
   248  	if req.Serial == "0000000000000000000000000000000000ee" {
   249  		return &corepb.CertificateStatus{
   250  			Status: string(core.OCSPStatusGood),
   251  		}, nil
   252  	} else if req.Serial == "0000000000000000000000000000000000b2" {
   253  		return &corepb.CertificateStatus{
   254  			Status: string(core.OCSPStatusRevoked),
   255  		}, nil
   256  	} else {
   257  		return nil, errors.New("no cert status")
   258  	}
   259  }
   260  
   261  func (sa *StorageAuthorityReadOnly) SetCertificateStatusReady(ctx context.Context, req *sapb.Serial, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   262  	return nil, status.Error(codes.Unimplemented, "unimplemented mock")
   263  
   264  }
   265  
   266  // GetRevocationStatus is a mock
   267  func (sa *StorageAuthorityReadOnly) GetRevocationStatus(_ context.Context, req *sapb.Serial, _ ...grpc.CallOption) (*sapb.RevocationStatus, error) {
   268  	return nil, nil
   269  }
   270  
   271  // SerialsForIncident is a mock
   272  func (sa *StorageAuthorityReadOnly) SerialsForIncident(ctx context.Context, _ *sapb.SerialsForIncidentRequest, _ ...grpc.CallOption) (sapb.StorageAuthorityReadOnly_SerialsForIncidentClient, error) {
   273  	return nil, nil
   274  }
   275  
   276  // SerialsForIncident is a mock
   277  func (sa *StorageAuthority) SerialsForIncident(ctx context.Context, _ *sapb.SerialsForIncidentRequest, _ ...grpc.CallOption) (sapb.StorageAuthority_SerialsForIncidentClient, error) {
   278  	return nil, nil
   279  }
   280  
   281  // GetRevokedCerts is a mock
   282  func (sa *StorageAuthorityReadOnly) GetRevokedCerts(ctx context.Context, _ *sapb.GetRevokedCertsRequest, _ ...grpc.CallOption) (sapb.StorageAuthorityReadOnly_GetRevokedCertsClient, error) {
   283  	return nil, nil
   284  }
   285  
   286  // GetRevokedCerts is a mock
   287  func (sa *StorageAuthority) GetRevokedCerts(ctx context.Context, _ *sapb.GetRevokedCertsRequest, _ ...grpc.CallOption) (sapb.StorageAuthority_GetRevokedCertsClient, error) {
   288  	return nil, nil
   289  }
   290  
   291  // GetMaxExpiration is a mock
   292  func (sa *StorageAuthorityReadOnly) GetMaxExpiration(_ context.Context, req *emptypb.Empty, _ ...grpc.CallOption) (*timestamppb.Timestamp, error) {
   293  	return nil, nil
   294  }
   295  
   296  // AddPrecertificate is a mock
   297  func (sa *StorageAuthority) AddPrecertificate(ctx context.Context, req *sapb.AddCertificateRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   298  	return nil, nil
   299  }
   300  
   301  // AddSerial is a mock
   302  func (sa *StorageAuthority) AddSerial(ctx context.Context, req *sapb.AddSerialRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   303  	return nil, nil
   304  }
   305  
   306  // AddCertificate is a mock
   307  func (sa *StorageAuthority) AddCertificate(_ context.Context, _ *sapb.AddCertificateRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   308  	return nil, nil
   309  }
   310  
   311  // NewRegistration is a mock
   312  func (sa *StorageAuthority) NewRegistration(_ context.Context, _ *corepb.Registration, _ ...grpc.CallOption) (*corepb.Registration, error) {
   313  	return &corepb.Registration{}, nil
   314  }
   315  
   316  // UpdateRegistration is a mock
   317  func (sa *StorageAuthority) UpdateRegistration(_ context.Context, _ *corepb.Registration, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   318  	return &emptypb.Empty{}, nil
   319  }
   320  
   321  // CountFQDNSets is a mock
   322  func (sa *StorageAuthorityReadOnly) CountFQDNSets(_ context.Context, _ *sapb.CountFQDNSetsRequest, _ ...grpc.CallOption) (*sapb.Count, error) {
   323  	return &sapb.Count{}, nil
   324  }
   325  
   326  // FQDNSetTimestampsForWindow is a mock
   327  func (sa *StorageAuthorityReadOnly) FQDNSetTimestampsForWindow(_ context.Context, _ *sapb.CountFQDNSetsRequest, _ ...grpc.CallOption) (*sapb.Timestamps, error) {
   328  	return &sapb.Timestamps{}, nil
   329  }
   330  
   331  // FQDNSetExists is a mock
   332  func (sa *StorageAuthorityReadOnly) FQDNSetExists(_ context.Context, _ *sapb.FQDNSetExistsRequest, _ ...grpc.CallOption) (*sapb.Exists, error) {
   333  	return &sapb.Exists{Exists: false}, nil
   334  }
   335  
   336  func (sa *StorageAuthorityReadOnly) PreviousCertificateExists(_ context.Context, _ *sapb.PreviousCertificateExistsRequest, _ ...grpc.CallOption) (*sapb.Exists, error) {
   337  	return &sapb.Exists{Exists: false}, nil
   338  }
   339  
   340  // CountCertificatesByNames is a mock
   341  func (sa *StorageAuthorityReadOnly) CountCertificatesByNames(_ context.Context, _ *sapb.CountCertificatesByNamesRequest, _ ...grpc.CallOption) (*sapb.CountByNames, error) {
   342  	return &sapb.CountByNames{}, nil
   343  }
   344  
   345  // CountRegistrationsByIP is a mock
   346  func (sa *StorageAuthorityReadOnly) CountRegistrationsByIP(_ context.Context, _ *sapb.CountRegistrationsByIPRequest, _ ...grpc.CallOption) (*sapb.Count, error) {
   347  	return &sapb.Count{}, nil
   348  }
   349  
   350  // CountRegistrationsByIPRange is a mock
   351  func (sa *StorageAuthorityReadOnly) CountRegistrationsByIPRange(_ context.Context, _ *sapb.CountRegistrationsByIPRequest, _ ...grpc.CallOption) (*sapb.Count, error) {
   352  	return &sapb.Count{}, nil
   353  }
   354  
   355  // CountOrders is a mock
   356  func (sa *StorageAuthorityReadOnly) CountOrders(_ context.Context, _ *sapb.CountOrdersRequest, _ ...grpc.CallOption) (*sapb.Count, error) {
   357  	return &sapb.Count{}, nil
   358  }
   359  
   360  // DeactivateRegistration is a mock
   361  func (sa *StorageAuthority) DeactivateRegistration(_ context.Context, _ *sapb.RegistrationID, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   362  	return &emptypb.Empty{}, nil
   363  }
   364  
   365  // NewOrderAndAuthzs is a mock
   366  func (sa *StorageAuthority) NewOrderAndAuthzs(_ context.Context, req *sapb.NewOrderAndAuthzsRequest, _ ...grpc.CallOption) (*corepb.Order, error) {
   367  	now := time.Now()
   368  	response := &corepb.Order{
   369  		// Fields from the input new order request.
   370  		RegistrationID:   req.NewOrder.RegistrationID,
   371  		ExpiresNS:        req.NewOrder.ExpiresNS,
   372  		Expires:          req.NewOrder.Expires,
   373  		Names:            req.NewOrder.Names,
   374  		V2Authorizations: req.NewOrder.V2Authorizations,
   375  		// Mock new fields generated by the database transaction.
   376  		Id:        rand.Int63(),
   377  		CreatedNS: now.UnixNano(),
   378  		Created:   timestamppb.New(now),
   379  		// A new order is never processing because it can't have been finalized yet.
   380  		BeganProcessing: false,
   381  		Status:          string(core.StatusPending),
   382  	}
   383  	return response, nil
   384  }
   385  
   386  // SetOrderProcessing is a mock
   387  func (sa *StorageAuthority) SetOrderProcessing(_ context.Context, req *sapb.OrderRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   388  	return &emptypb.Empty{}, nil
   389  }
   390  
   391  // SetOrderError is a mock
   392  func (sa *StorageAuthority) SetOrderError(_ context.Context, req *sapb.SetOrderErrorRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   393  	return &emptypb.Empty{}, nil
   394  }
   395  
   396  // FinalizeOrder is a mock
   397  func (sa *StorageAuthority) FinalizeOrder(_ context.Context, req *sapb.FinalizeOrderRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   398  	return &emptypb.Empty{}, nil
   399  }
   400  
   401  // GetOrder is a mock
   402  func (sa *StorageAuthorityReadOnly) GetOrder(_ context.Context, req *sapb.OrderRequest, _ ...grpc.CallOption) (*corepb.Order, error) {
   403  	if req.Id == 2 {
   404  		return nil, berrors.NotFoundError("bad")
   405  	} else if req.Id == 3 {
   406  		return nil, errors.New("very bad")
   407  	}
   408  
   409  	created := sa.clk.Now().AddDate(-30, 0, 0)
   410  	exp := sa.clk.Now().AddDate(30, 0, 0)
   411  	validOrder := &corepb.Order{
   412  		Id:                req.Id,
   413  		RegistrationID:    1,
   414  		CreatedNS:         created.UnixNano(),
   415  		Created:           timestamppb.New(created),
   416  		ExpiresNS:         exp.UnixNano(),
   417  		Expires:           timestamppb.New(exp),
   418  		Names:             []string{"example.com"},
   419  		Status:            string(core.StatusValid),
   420  		V2Authorizations:  []int64{1},
   421  		CertificateSerial: "serial",
   422  		Error:             nil,
   423  	}
   424  
   425  	// Order ID doesn't have a certificate serial yet
   426  	if req.Id == 4 {
   427  		validOrder.Status = string(core.StatusPending)
   428  		validOrder.Id = req.Id
   429  		validOrder.CertificateSerial = ""
   430  		validOrder.Error = nil
   431  		return validOrder, nil
   432  	}
   433  
   434  	// Order ID 6 belongs to reg ID 6
   435  	if req.Id == 6 {
   436  		validOrder.Id = 6
   437  		validOrder.RegistrationID = 6
   438  	}
   439  
   440  	// Order ID 7 is ready, but expired
   441  	if req.Id == 7 {
   442  		validOrder.Status = string(core.StatusReady)
   443  		validOrder.ExpiresNS = sa.clk.Now().AddDate(-30, 0, 0).Unix()
   444  	}
   445  
   446  	if req.Id == 8 {
   447  		validOrder.Status = string(core.StatusReady)
   448  	}
   449  
   450  	// Order 9 is fresh
   451  	if req.Id == 9 {
   452  		validOrder.CreatedNS = sa.clk.Now().AddDate(0, 0, 1).Unix()
   453  	}
   454  
   455  	// Order 10 is processing
   456  	if req.Id == 10 {
   457  		validOrder.Status = string(core.StatusProcessing)
   458  	}
   459  
   460  	return validOrder, nil
   461  }
   462  
   463  func (sa *StorageAuthorityReadOnly) GetOrderForNames(_ context.Context, _ *sapb.GetOrderForNamesRequest, _ ...grpc.CallOption) (*corepb.Order, error) {
   464  	return nil, nil
   465  }
   466  
   467  func (sa *StorageAuthority) FinalizeAuthorization2(ctx context.Context, req *sapb.FinalizeAuthorizationRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   468  	return &emptypb.Empty{}, nil
   469  }
   470  
   471  func (sa *StorageAuthority) DeactivateAuthorization2(ctx context.Context, req *sapb.AuthorizationID2, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   472  	return nil, nil
   473  }
   474  
   475  func (sa *StorageAuthorityReadOnly) CountPendingAuthorizations2(ctx context.Context, req *sapb.RegistrationID, _ ...grpc.CallOption) (*sapb.Count, error) {
   476  	return &sapb.Count{}, nil
   477  }
   478  
   479  func (sa *StorageAuthorityReadOnly) GetValidOrderAuthorizations2(ctx context.Context, req *sapb.GetValidOrderAuthorizationsRequest, _ ...grpc.CallOption) (*sapb.Authorizations, error) {
   480  	return nil, nil
   481  }
   482  
   483  func (sa *StorageAuthorityReadOnly) CountInvalidAuthorizations2(ctx context.Context, req *sapb.CountInvalidAuthorizationsRequest, _ ...grpc.CallOption) (*sapb.Count, error) {
   484  	return &sapb.Count{}, nil
   485  }
   486  
   487  func (sa *StorageAuthorityReadOnly) GetValidAuthorizations2(ctx context.Context, req *sapb.GetValidAuthorizationsRequest, _ ...grpc.CallOption) (*sapb.Authorizations, error) {
   488  	if req.RegistrationID != 1 && req.RegistrationID != 5 && req.RegistrationID != 4 {
   489  		return &sapb.Authorizations{}, nil
   490  	}
   491  	now := time.Unix(0, req.NowNS)
   492  	auths := &sapb.Authorizations{}
   493  	for _, name := range req.Domains {
   494  		exp := now.AddDate(100, 0, 0)
   495  		authzPB, err := bgrpc.AuthzToPB(core.Authorization{
   496  			Status:         core.StatusValid,
   497  			RegistrationID: req.RegistrationID,
   498  			Expires:        &exp,
   499  			Identifier: identifier.ACMEIdentifier{
   500  				Type:  "dns",
   501  				Value: name,
   502  			},
   503  			Challenges: []core.Challenge{
   504  				{
   505  					Status:    core.StatusValid,
   506  					Type:      core.ChallengeTypeDNS01,
   507  					Token:     "exampleToken",
   508  					Validated: &now,
   509  				},
   510  			},
   511  		})
   512  		if err != nil {
   513  			return nil, err
   514  		}
   515  		auths.Authz = append(auths.Authz, &sapb.Authorizations_MapElement{
   516  			Domain: name,
   517  			Authz:  authzPB,
   518  		})
   519  	}
   520  	return auths, nil
   521  }
   522  
   523  func (sa *StorageAuthorityReadOnly) GetAuthorizations2(ctx context.Context, req *sapb.GetAuthorizationsRequest, _ ...grpc.CallOption) (*sapb.Authorizations, error) {
   524  	return &sapb.Authorizations{}, nil
   525  }
   526  
   527  func (sa *StorageAuthorityReadOnly) GetPendingAuthorization2(ctx context.Context, req *sapb.GetPendingAuthorizationRequest, _ ...grpc.CallOption) (*corepb.Authorization, error) {
   528  	return nil, nil
   529  }
   530  
   531  var (
   532  	authzIdValid       = int64(1)
   533  	authzIdPending     = int64(2)
   534  	authzIdExpired     = int64(3)
   535  	authzIdErrorResult = int64(4)
   536  	authzIdDiffAccount = int64(5)
   537  )
   538  
   539  // GetAuthorization2 is a mock
   540  func (sa *StorageAuthorityReadOnly) GetAuthorization2(ctx context.Context, id *sapb.AuthorizationID2, _ ...grpc.CallOption) (*corepb.Authorization, error) {
   541  	authz := core.Authorization{
   542  		Status:         core.StatusValid,
   543  		RegistrationID: 1,
   544  		Identifier:     identifier.DNSIdentifier("not-an-example.com"),
   545  		Challenges: []core.Challenge{
   546  			{
   547  				Status: "pending",
   548  				Token:  "token",
   549  				Type:   "dns",
   550  			},
   551  		},
   552  	}
   553  
   554  	switch id.Id {
   555  	case authzIdValid:
   556  		exp := sa.clk.Now().AddDate(100, 0, 0)
   557  		authz.Expires = &exp
   558  		authz.ID = fmt.Sprintf("%d", authzIdValid)
   559  		return bgrpc.AuthzToPB(authz)
   560  	case authzIdPending:
   561  		exp := sa.clk.Now().AddDate(100, 0, 0)
   562  		authz.Expires = &exp
   563  		authz.ID = fmt.Sprintf("%d", authzIdPending)
   564  		authz.Status = core.StatusPending
   565  		return bgrpc.AuthzToPB(authz)
   566  	case authzIdExpired:
   567  		exp := sa.clk.Now().AddDate(0, -1, 0)
   568  		authz.Expires = &exp
   569  		authz.ID = fmt.Sprintf("%d", authzIdExpired)
   570  		return bgrpc.AuthzToPB(authz)
   571  	case authzIdErrorResult:
   572  		return nil, fmt.Errorf("unspecified database error")
   573  	case authzIdDiffAccount:
   574  		exp := sa.clk.Now().AddDate(100, 0, 0)
   575  		authz.RegistrationID = 2
   576  		authz.Expires = &exp
   577  		authz.ID = fmt.Sprintf("%d", authzIdDiffAccount)
   578  		return bgrpc.AuthzToPB(authz)
   579  	}
   580  
   581  	return nil, berrors.NotFoundError("no authorization found with id %q", id)
   582  }
   583  
   584  // RevokeCertificate is a mock
   585  func (sa *StorageAuthority) RevokeCertificate(ctx context.Context, req *sapb.RevokeCertificateRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   586  	return nil, nil
   587  }
   588  
   589  // UpdateRevokedCertificate is a mock
   590  func (sa *StorageAuthority) UpdateRevokedCertificate(ctx context.Context, req *sapb.RevokeCertificateRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   591  	return nil, nil
   592  }
   593  
   594  // AddBlockedKey is a mock
   595  func (sa *StorageAuthority) AddBlockedKey(ctx context.Context, req *sapb.AddBlockedKeyRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   596  	return &emptypb.Empty{}, nil
   597  }
   598  
   599  // KeyBlocked is a mock
   600  func (sa *StorageAuthorityReadOnly) KeyBlocked(ctx context.Context, req *sapb.KeyBlockedRequest, _ ...grpc.CallOption) (*sapb.Exists, error) {
   601  	return &sapb.Exists{Exists: false}, nil
   602  }
   603  
   604  // IncidentsForSerial is a mock.
   605  func (sa *StorageAuthorityReadOnly) IncidentsForSerial(ctx context.Context, req *sapb.Serial, _ ...grpc.CallOption) (*sapb.Incidents, error) {
   606  	return &sapb.Incidents{}, nil
   607  }
   608  
   609  // LeaseCRLShard is a mock.
   610  func (sa *StorageAuthority) LeaseCRLShard(ctx context.Context, req *sapb.LeaseCRLShardRequest, _ ...grpc.CallOption) (*sapb.LeaseCRLShardResponse, error) {
   611  	return nil, errors.New("unimplemented")
   612  }
   613  
   614  // UpdateCRLShard is a mock.
   615  func (sa *StorageAuthority) UpdateCRLShard(ctx context.Context, req *sapb.UpdateCRLShardRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) {
   616  	return nil, errors.New("unimplemented")
   617  }
   618  
   619  // PublisherClient is a mock
   620  type PublisherClient struct {
   621  	// empty
   622  }
   623  
   624  // SubmitToSingleCTWithResult is a mock
   625  func (*PublisherClient) SubmitToSingleCTWithResult(_ context.Context, _ *pubpb.Request, _ ...grpc.CallOption) (*pubpb.Result, error) {
   626  	return &pubpb.Result{}, nil
   627  }
   628  
   629  // Mailer is a mock
   630  type Mailer struct {
   631  	sync.Mutex
   632  	Messages []MailerMessage
   633  }
   634  
   635  var _ mail.Mailer = &Mailer{}
   636  
   637  // mockMailerConn is a mock that satisfies the mail.Conn interface
   638  type mockMailerConn struct {
   639  	parent *Mailer
   640  }
   641  
   642  var _ mail.Conn = &mockMailerConn{}
   643  
   644  // MailerMessage holds the captured emails from SendMail()
   645  type MailerMessage struct {
   646  	To      string
   647  	Subject string
   648  	Body    string
   649  }
   650  
   651  // Clear removes any previously recorded messages
   652  func (m *Mailer) Clear() {
   653  	m.Lock()
   654  	defer m.Unlock()
   655  	m.Messages = nil
   656  }
   657  
   658  // SendMail is a mock
   659  func (m *mockMailerConn) SendMail(to []string, subject, msg string) error {
   660  	m.parent.Lock()
   661  	defer m.parent.Unlock()
   662  	for _, rcpt := range to {
   663  		m.parent.Messages = append(m.parent.Messages, MailerMessage{
   664  			To:      rcpt,
   665  			Subject: subject,
   666  			Body:    msg,
   667  		})
   668  	}
   669  	return nil
   670  }
   671  
   672  // Close is a mock
   673  func (m *mockMailerConn) Close() error {
   674  	return nil
   675  }
   676  
   677  // Connect is a mock
   678  func (m *Mailer) Connect() (mail.Conn, error) {
   679  	return &mockMailerConn{parent: m}, nil
   680  }
   681  

View as plain text