github.com/hairyhenderson/gomplate/v3@v3.11.7/internal/tests/integration/test_ec2_utils.go (about)

     1  package integration
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/rand"
     6  	"crypto/rsa"
     7  	"crypto/x509"
     8  	"crypto/x509/pkix"
     9  	"encoding/pem"
    10  	"log"
    11  	"math/big"
    12  	"net/http"
    13  	"time"
    14  
    15  	"github.com/fullsailor/pkcs7"
    16  )
    17  
    18  const instanceDocument = `{
    19      "devpayProductCodes" : null,
    20      "availabilityZone" : "xx-test-1b",
    21      "privateIp" : "10.1.2.3",
    22      "version" : "2010-08-31",
    23      "instanceId" : "i-00000000000000000",
    24      "billingProducts" : null,
    25      "instanceType" : "t2.micro",
    26      "accountId" : "1",
    27      "imageId" : "ami-00000000",
    28      "pendingTime" : "2000-00-01T0:00:00Z",
    29      "architecture" : "x86_64",
    30      "kernelId" : null,
    31      "ramdiskId" : null,
    32      "region" : "xx-test-1"
    33  }`
    34  
    35  func instanceDocumentHandler(w http.ResponseWriter, _ *http.Request) {
    36  	w.Header().Set("Content-Type", "application/json")
    37  	_, err := w.Write([]byte(instanceDocument))
    38  	if err != nil {
    39  		w.WriteHeader(500)
    40  	}
    41  }
    42  
    43  func certificateGenerate() (priv *rsa.PrivateKey, derBytes []byte, err error) {
    44  	priv, err = rsa.GenerateKey(rand.Reader, 2048)
    45  	if err != nil {
    46  		log.Fatalf("failed to generate private key: %s", err)
    47  	}
    48  
    49  	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
    50  	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
    51  	if err != nil {
    52  		log.Fatalf("failed to generate serial number: %s", err)
    53  	}
    54  
    55  	template := x509.Certificate{
    56  		SerialNumber: serialNumber,
    57  		Subject: pkix.Name{
    58  			Organization: []string{"Test"},
    59  		},
    60  		NotBefore: time.Now().Add(-24 * time.Hour),
    61  		NotAfter:  time.Now().Add(365 * 24 * time.Hour),
    62  	}
    63  
    64  	derBytes, err = x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
    65  	if err != nil {
    66  		log.Fatalf("Failed to create certificate: %s", err)
    67  	}
    68  
    69  	return priv, derBytes, err
    70  }
    71  
    72  func pkcsHandler(priv *rsa.PrivateKey, derBytes []byte) func(http.ResponseWriter, *http.Request) {
    73  	return func(w http.ResponseWriter, r *http.Request) {
    74  		cert, err := x509.ParseCertificate(derBytes)
    75  		if err != nil {
    76  			log.Fatalf("Cannot decode certificate: %s", err)
    77  		}
    78  
    79  		// Initialize a SignedData struct with content to be signed
    80  		signedData, err := pkcs7.NewSignedData([]byte(instanceDocument))
    81  		if err != nil {
    82  			log.Fatalf("Cannot initialize signed data: %s", err)
    83  		}
    84  
    85  		// Add the signing cert and private key
    86  		if err = signedData.AddSigner(cert, priv, pkcs7.SignerInfoConfig{}); err != nil {
    87  			log.Fatalf("Cannot add signer: %s", err)
    88  		}
    89  
    90  		// Finish() to obtain the signature bytes
    91  		detachedSignature, err := signedData.Finish()
    92  		if err != nil {
    93  			log.Fatalf("Cannot finish signing data: %s", err)
    94  		}
    95  
    96  		encoded := pem.EncodeToMemory(&pem.Block{Type: "PKCS7", Bytes: detachedSignature})
    97  
    98  		encoded = bytes.TrimPrefix(encoded, []byte("-----BEGIN PKCS7-----\n"))
    99  		encoded = bytes.TrimSuffix(encoded, []byte("\n-----END PKCS7-----\n"))
   100  
   101  		w.Header().Set("Content-Type", "text/plain")
   102  		_, err = w.Write(encoded)
   103  		if err != nil {
   104  			w.WriteHeader(500)
   105  		}
   106  	}
   107  }
   108  
   109  func stsHandler(w http.ResponseWriter, _ *http.Request) {
   110  	w.Header().Set("Content-Type", "text/xml")
   111  	_, err := w.Write([]byte(`<GetCallerIdentityResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
   112    <GetCallerIdentityResult>
   113     <Arn>arn:aws:iam::1:user/Test</Arn>
   114      <UserId>AKIAI44QH8DHBEXAMPLE</UserId>
   115      <Account>1</Account>
   116    </GetCallerIdentityResult>
   117    <ResponseMetadata>
   118      <RequestId>01234567-89ab-cdef-0123-456789abcdef</RequestId>
   119    </ResponseMetadata>
   120  </GetCallerIdentityResponse>`))
   121  	if err != nil {
   122  		w.WriteHeader(500)
   123  	}
   124  }
   125  
   126  func ec2Handler(w http.ResponseWriter, _ *http.Request) {
   127  	w.Header().Set("Content-Type", "text/xml")
   128  	_, err := w.Write([]byte(`<DescribeInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2016-11-15/">
   129      <requestId>8f7724cf-496f-496e-8fe3-example</requestId>
   130      <reservationSet>
   131          <item>
   132              <reservationId>r-1234567890abcdef0</reservationId>
   133              <ownerId>123456789012</ownerId>
   134              <groupSet/>
   135              <instancesSet>
   136                  <item>
   137                      <instanceId>i-00000000000000000</instanceId>
   138                      <imageId>ami-00000000</imageId>
   139                      <instanceState>
   140                          <code>16</code>
   141                          <name>running</name>
   142                      </instanceState>
   143                      <privateDnsName>ip-192-168-1-88.eu-west-1.compute.internal</privateDnsName>
   144                      <dnsName>ec2-54-194-252-215.eu-west-1.compute.amazonaws.com</dnsName>
   145                      <reason/>
   146                      <keyName>my_keypair</keyName>
   147                      <amiLaunchIndex>0</amiLaunchIndex>
   148                      <productCodes/>
   149                      <instanceType>t2.micro</instanceType>
   150                      <launchTime>2015-12-22T10:44:05.000Z</launchTime>
   151                      <placement>
   152                          <availabilityZone>eu-west-1c</availabilityZone>
   153                          <groupName/>
   154                          <tenancy>default</tenancy>
   155                      </placement>
   156                      <monitoring>
   157                          <state>disabled</state>
   158                      </monitoring>
   159                      <subnetId>subnet-56f5f633</subnetId>
   160                      <vpcId>vpc-11112222</vpcId>
   161                      <privateIpAddress>192.168.1.88</privateIpAddress>
   162                      <ipAddress>54.194.252.215</ipAddress>
   163                      <sourceDestCheck>true</sourceDestCheck>
   164                      <groupSet>
   165                          <item>
   166                              <groupId>sg-e4076980</groupId>
   167                              <groupName>SecurityGroup1</groupName>
   168                          </item>
   169                      </groupSet>
   170                      <architecture>x86_64</architecture>
   171                      <rootDeviceType>ebs</rootDeviceType>
   172                      <rootDeviceName>/dev/xvda</rootDeviceName>
   173                      <blockDeviceMapping>
   174                          <item>
   175                              <deviceName>/dev/xvda</deviceName>
   176                              <ebs>
   177                                  <volumeId>vol-1234567890abcdef0</volumeId>
   178                                  <status>attached</status>
   179                                  <attachTime>2015-12-22T10:44:09.000Z</attachTime>
   180                                  <deleteOnTermination>true</deleteOnTermination>
   181                              </ebs>
   182                          </item>
   183                      </blockDeviceMapping>
   184                      <virtualizationType>hvm</virtualizationType>
   185                      <clientToken>xMcwG14507example</clientToken>
   186                      <tagSet>
   187                          <item>
   188                              <key>Name</key>
   189                              <value>Server_1</value>
   190                          </item>
   191                      </tagSet>
   192                      <hypervisor>xen</hypervisor>
   193                      <networkInterfaceSet>
   194                          <item>
   195                              <networkInterfaceId>eni-551ba033</networkInterfaceId>
   196                              <subnetId>subnet-56f5f633</subnetId>
   197                              <vpcId>vpc-11112222</vpcId>
   198                              <description>Primary network interface</description>
   199                              <ownerId>123456789012</ownerId>
   200                              <status>in-use</status>
   201                              <macAddress>02:dd:2c:5e:01:69</macAddress>
   202                              <privateIpAddress>192.168.1.88</privateIpAddress>
   203                              <privateDnsName>ip-192-168-1-88.eu-west-1.compute.internal</privateDnsName>
   204                              <sourceDestCheck>true</sourceDestCheck>
   205                              <groupSet>
   206                                  <item>
   207                                      <groupId>sg-e4076980</groupId>
   208                                      <groupName>SecurityGroup1</groupName>
   209                                  </item>
   210                              </groupSet>
   211                              <attachment>
   212                                  <attachmentId>eni-attach-39697adc</attachmentId>
   213                                  <deviceIndex>0</deviceIndex>
   214                                  <status>attached</status>
   215                                  <attachTime>2015-12-22T10:44:05.000Z</attachTime>
   216                                  <deleteOnTermination>true</deleteOnTermination>
   217                              </attachment>
   218                              <association>
   219                                  <publicIp>54.194.252.215</publicIp>
   220                                  <publicDnsName>ec2-54-194-252-215.eu-west-1.compute.amazonaws.com</publicDnsName>
   221                                  <ipOwnerId>amazon</ipOwnerId>
   222                              </association>
   223                              <privateIpAddressesSet>
   224                                  <item>
   225                                      <privateIpAddress>192.168.1.88</privateIpAddress>
   226                                      <privateDnsName>ip-192-168-1-88.eu-west-1.compute.internal</privateDnsName>
   227                                      <primary>true</primary>
   228                                      <association>
   229                                      <publicIp>54.194.252.215</publicIp>
   230                                      <publicDnsName>ec2-54-194-252-215.eu-west-1.compute.amazonaws.com</publicDnsName>
   231                                      <ipOwnerId>amazon</ipOwnerId>
   232                                      </association>
   233                                  </item>
   234                              </privateIpAddressesSet>
   235                              <ipv6AddressesSet>
   236                                 <item>
   237                                     <ipv6Address>2001:db8:1234:1a2b::123</ipv6Address>
   238                                 </item>
   239                             </ipv6AddressesSet>
   240                          </item>
   241                      </networkInterfaceSet>
   242                      <ebsOptimized>false</ebsOptimized>
   243                  </item>
   244              </instancesSet>
   245          </item>
   246      </reservationSet>
   247  </DescribeInstancesResponse>`))
   248  	if err != nil {
   249  		w.WriteHeader(500)
   250  	}
   251  }