github.com/Ne0nd0g/gophish@v0.7.1-0.20190220040016-11493024a07d/controllers/api_test.go (about)

     1  package controllers
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"net/http"
     8  	"net/http/httptest"
     9  	"os"
    10  	"testing"
    11  
    12  	"github.com/gophish/gophish/config"
    13  	"github.com/gophish/gophish/models"
    14  	"github.com/stretchr/testify/suite"
    15  )
    16  
    17  // ControllersSuite is a suite of tests to cover API related functions
    18  type ControllersSuite struct {
    19  	suite.Suite
    20  	apiKey      string
    21  	config      *config.Config
    22  	adminServer *httptest.Server
    23  	phishServer *httptest.Server
    24  }
    25  
    26  func (s *ControllersSuite) SetupSuite() {
    27  	conf := &config.Config{
    28  		DBName:         "sqlite3",
    29  		DBPath:         ":memory:",
    30  		MigrationsPath: "../db/db_sqlite3/migrations/",
    31  	}
    32  	err := models.Setup(conf)
    33  	if err != nil {
    34  		s.T().Fatalf("Failed creating database: %v", err)
    35  	}
    36  	s.config = conf
    37  	s.Nil(err)
    38  	// Setup the admin server for use in testing
    39  	s.adminServer = httptest.NewUnstartedServer(NewAdminServer(s.config.AdminConf).server.Handler)
    40  	s.adminServer.Config.Addr = s.config.AdminConf.ListenURL
    41  	s.adminServer.Start()
    42  	// Get the API key to use for these tests
    43  	u, err := models.GetUser(1)
    44  	s.Nil(err)
    45  	s.apiKey = u.ApiKey
    46  	// Start the phishing server
    47  	s.phishServer = httptest.NewUnstartedServer(NewPhishingServer(s.config.PhishConf).server.Handler)
    48  	s.phishServer.Config.Addr = s.config.PhishConf.ListenURL
    49  	s.phishServer.Start()
    50  	// Move our cwd up to the project root for help with resolving
    51  	// static assets
    52  	err = os.Chdir("../")
    53  	s.Nil(err)
    54  }
    55  
    56  func (s *ControllersSuite) TearDownTest() {
    57  	campaigns, _ := models.GetCampaigns(1)
    58  	for _, campaign := range campaigns {
    59  		models.DeleteCampaign(campaign.Id)
    60  	}
    61  }
    62  
    63  func (s *ControllersSuite) SetupTest() {
    64  	// Add a group
    65  	group := models.Group{Name: "Test Group"}
    66  	group.Targets = []models.Target{
    67  		models.Target{BaseRecipient: models.BaseRecipient{Email: "test1@example.com", FirstName: "First", LastName: "Example"}},
    68  		models.Target{BaseRecipient: models.BaseRecipient{Email: "test2@example.com", FirstName: "Second", LastName: "Example"}},
    69  	}
    70  	group.UserId = 1
    71  	models.PostGroup(&group)
    72  
    73  	// Add a template
    74  	t := models.Template{Name: "Test Template"}
    75  	t.Subject = "Test subject"
    76  	t.Text = "Text text"
    77  	t.HTML = "<html>Test</html>"
    78  	t.UserId = 1
    79  	models.PostTemplate(&t)
    80  
    81  	// Add a landing page
    82  	p := models.Page{Name: "Test Page"}
    83  	p.HTML = "<html>Test</html>"
    84  	p.UserId = 1
    85  	models.PostPage(&p)
    86  
    87  	// Add a sending profile
    88  	smtp := models.SMTP{Name: "Test Page"}
    89  	smtp.UserId = 1
    90  	smtp.Host = "example.com"
    91  	smtp.FromAddress = "test@test.com"
    92  	models.PostSMTP(&smtp)
    93  
    94  	// Setup and "launch" our campaign
    95  	// Set the status such that no emails are attempted
    96  	c := models.Campaign{Name: "Test campaign"}
    97  	c.UserId = 1
    98  	c.Template = t
    99  	c.Page = p
   100  	c.SMTP = smtp
   101  	c.Groups = []models.Group{group}
   102  	models.PostCampaign(&c, c.UserId)
   103  	c.UpdateStatus(models.CampaignEmailsSent)
   104  }
   105  
   106  func (s *ControllersSuite) TestRequireAPIKey() {
   107  	resp, err := http.Post(fmt.Sprintf("%s/api/import/site", s.adminServer.URL), "application/json", nil)
   108  	s.Nil(err)
   109  	defer resp.Body.Close()
   110  	s.Equal(resp.StatusCode, http.StatusUnauthorized)
   111  }
   112  
   113  func (s *ControllersSuite) TestInvalidAPIKey() {
   114  	resp, err := http.Get(fmt.Sprintf("%s/api/groups/?api_key=%s", s.adminServer.URL, "bogus-api-key"))
   115  	s.Nil(err)
   116  	defer resp.Body.Close()
   117  	s.Equal(resp.StatusCode, http.StatusUnauthorized)
   118  }
   119  
   120  func (s *ControllersSuite) TestBearerToken() {
   121  	req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/groups/", s.adminServer.URL), nil)
   122  	s.Nil(err)
   123  	req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", s.apiKey))
   124  	resp, err := http.DefaultClient.Do(req)
   125  	s.Nil(err)
   126  	defer resp.Body.Close()
   127  	s.Equal(resp.StatusCode, http.StatusOK)
   128  }
   129  
   130  func (s *ControllersSuite) TestSiteImportBaseHref() {
   131  	h := "<html><head></head><body><img src=\"/test.png\"/></body></html>"
   132  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   133  		fmt.Fprintln(w, h)
   134  	}))
   135  	hr := fmt.Sprintf("<html><head><base href=\"%s\"/></head><body><img src=\"/test.png\"/>\n</body></html>", ts.URL)
   136  	defer ts.Close()
   137  	resp, err := http.Post(fmt.Sprintf("%s/api/import/site?api_key=%s", s.adminServer.URL, s.apiKey), "application/json",
   138  		bytes.NewBuffer([]byte(fmt.Sprintf(`
   139  			{
   140  				"url" : "%s",
   141  				"include_resources" : false
   142  			}
   143  		`, ts.URL))))
   144  	s.Nil(err)
   145  	defer resp.Body.Close()
   146  	cs := cloneResponse{}
   147  	err = json.NewDecoder(resp.Body).Decode(&cs)
   148  	s.Nil(err)
   149  	s.Equal(cs.HTML, hr)
   150  }
   151  
   152  func (s *ControllersSuite) TearDownSuite() {
   153  	// Tear down the admin and phishing servers
   154  	s.adminServer.Close()
   155  	s.phishServer.Close()
   156  }
   157  
   158  func TestControllerSuite(t *testing.T) {
   159  	suite.Run(t, new(ControllersSuite))
   160  }