Add tests for access command

This commit is contained in:
9seconds
2021-03-12 21:57:53 +03:00
parent 546a5849f3
commit 185baf6bc9
8 changed files with 252 additions and 29 deletions
+25 -13
View File
@@ -26,6 +26,7 @@ type accessResponse struct {
type accessResponseURLs struct {
IP net.IP `json:"ip"`
Port uint `json:"port"`
TgURL string `json:"tg_url"`
TgQrCode string `json:"tg_qrcode"`
TmeURL string `json:"tme_url"`
@@ -33,10 +34,11 @@ type accessResponseURLs struct {
}
type Access struct {
base
base `kong:"-"`
ConfigPath string `arg required type:"existingfile" help:"Path to the configuration file." name:"config-path"` // nolint: lll, govet
Hex bool `help:"Print secret in hex encoding."`
ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"` // nolint: lll
Port uint `kong:"help='Port number. Default port is taken from configuration file, bind-to parameter',type:'uint'"`
Hex bool `kong:"help='Print secret in hex encoding.'"`
}
func (c *Access) Run(cli *CLI, version string) error {
@@ -44,9 +46,13 @@ func (c *Access) Run(cli *CLI, version string) error {
return fmt.Errorf("cannot init config: %w", err)
}
return c.Execute(cli)
}
func (c *Access) Execute(cli *CLI) error {
resp := &accessResponse{}
resp.Secret.Base64 = c.conf.Secret.Base64()
resp.Secret.Hex = c.conf.Secret.Hex()
resp.Secret.Base64 = c.Config.Secret.Base64()
resp.Secret.Hex = c.Config.Secret.Hex()
wg := &sync.WaitGroup{}
wg.Add(2) // nolint: gomnd
@@ -54,7 +60,7 @@ func (c *Access) Run(cli *CLI, version string) error {
go func() {
defer wg.Done()
ip := c.conf.Network.PublicIP.IPv4.Value(nil)
ip := c.Config.Network.PublicIP.IPv4.Value(nil)
if ip == nil {
ip = c.getIP("tcp4")
}
@@ -69,7 +75,7 @@ func (c *Access) Run(cli *CLI, version string) error {
go func() {
defer wg.Done()
ip := c.conf.Network.PublicIP.IPv4.Value(nil)
ip := c.Config.Network.PublicIP.IPv6.Value(nil)
if ip == nil {
ip = c.getIP("tcp6")
}
@@ -95,8 +101,8 @@ func (c *Access) Run(cli *CLI, version string) error {
}
func (c *Access) getIP(protocol string) net.IP {
client := c.network.MakeHTTPClient(func(ctx context.Context, network, address string) (net.Conn, error) {
return c.network.DialContext(ctx, protocol, address)
client := c.Network.MakeHTTPClient(func(ctx context.Context, network, address string) (net.Conn, error) {
return c.Network.DialContext(ctx, protocol, address)
})
req, err := http.NewRequest(http.MethodGet, "https://ifconfig.co", nil) // nolint: noctx
@@ -133,20 +139,26 @@ func (c *Access) makeURLs(ip net.IP, cli *CLI) *accessResponseURLs {
return nil
}
portNo := cli.Access.Port
if portNo == 0 {
portNo = c.Config.BindTo.PortValue(0)
}
values := url.Values{}
values.Set("server", ip.String())
values.Set("port", strconv.Itoa(int(c.conf.BindTo.PortValue(0))))
values.Set("port", strconv.Itoa(int(portNo)))
if cli.Access.Hex {
values.Set("secret", c.conf.Secret.Hex())
values.Set("secret", c.Config.Secret.Hex())
} else {
values.Set("secret", c.conf.Secret.Base64())
values.Set("secret", c.Config.Secret.Base64())
}
urlQuery := values.Encode()
rv := &accessResponseURLs{
IP: ip,
IP: ip,
Port: portNo,
TgURL: (&url.URL{
Scheme: "tg",
Host: "proxy",
+205
View File
@@ -0,0 +1,205 @@
package cli_test
import (
"net/http"
"testing"
"github.com/9seconds/mtg/v2/config"
"github.com/9seconds/mtg/v2/mtglib"
"github.com/jarcoal/httpmock"
"github.com/stretchr/testify/suite"
"github.com/xeipuuv/gojsonschema"
)
var accressResponseJSONSchema = func() *gojsonschema.Schema {
schema, err := gojsonschema.NewSchema(gojsonschema.NewStringLoader(`
{
"type": "object",
"required": ["secret"],
"additionalProperties": true,
"properties": {
"secret": {
"type": "object",
"required": [
"hex",
"base64"
],
"additionalProperties": false,
"properties": {
"hex": {
"type": "string",
"minLength": 34
},
"base64": {
"type": "string",
"minLength": 10
}
}
},
"ipv4": {
"$ref": "#/definitions/ip"
},
"ipv6": {
"$ref": "#/definitions/ip"
}
},
"definitions": {
"ip": {
"type": "object",
"required": [
"ip",
"port",
"tg_url",
"tg_qrcode",
"tme_url",
"tme_qrcode"
],
"additionalProperties": false,
"properties": {
"ip": {
"type": "string",
"minLength": 1,
"anyOf": [
{
"format": "ipv4"
},
{
"format": "ipv6"
}
]
},
"port": {
"type": "integer",
"multipleOf": 1.0,
"exclusiveMinimum": 0,
"exclusiveMaximum": 65536
},
"tg_url": {
"type": "string",
"minLength": 1,
"format": "uri"
},
"tg_qrcode": {
"type": "string",
"minLength": 1,
"format": "uri"
},
"tme_url": {
"type": "string",
"minLength": 1,
"format": "uri"
},
"tme_qrcode": {
"type": "string",
"minLength": 1,
"format": "uri"
}
}
}
}
}
`))
if err != nil {
panic(err)
}
return schema
}()
type AccessTestSuite struct {
CommonTestSuite
}
func (suite *AccessTestSuite) SetupTest() {
suite.CommonTestSuite.SetupTest()
suite.cli.Access.Config = &config.Config{}
suite.cli.Access.Config.Secret = mtglib.GenerateSecret("google.com")
suite.cli.Access.Network = suite.networkMock
suite.NoError(
suite.cli.Access.Config.BindTo.UnmarshalText([]byte("0.0.0.0:80")))
}
func (suite *AccessTestSuite) TestGenerateNoCalls() {
suite.NoError(
suite.cli.Access.Config.Network.PublicIP.IPv4.UnmarshalText(
[]byte("10.0.0.10")))
suite.NoError(
suite.cli.Access.Config.Network.PublicIP.IPv6.UnmarshalText(
[]byte("2001:0db8:85a3:0000:0000:8a2e:0370:7334")))
output := suite.CaptureStdout(func() {
suite.NoError(suite.cli.Access.Execute(suite.cli))
})
validated, err := accressResponseJSONSchema.Validate(
gojsonschema.NewStringLoader(output))
suite.NoError(err)
suite.Empty(validated.Errors())
suite.True(validated.Valid())
suite.Contains(output, "10.0.0.10")
suite.Contains(output, "2001:db8:85a3::8a2e:370:7334")
suite.Contains(output, "ipv4")
suite.Contains(output, "ipv6")
suite.Contains(output, suite.cli.Access.Config.Secret.Base64())
suite.Contains(output, suite.cli.Access.Config.Secret.Hex())
}
func (suite *AccessTestSuite) TestGenerateIPv4Call() {
suite.NoError(
suite.cli.Access.Config.Network.PublicIP.IPv6.UnmarshalText(
[]byte("2001:0db8:85a3:0000:0000:8a2e:0370:7334")))
httpmock.RegisterResponder(http.MethodGet, "https://ifconfig.co",
httpmock.NewStringResponder(http.StatusOK, "10.11.12.13"))
output := suite.CaptureStdout(func() {
suite.NoError(suite.cli.Access.Execute(suite.cli))
})
validated, err := accressResponseJSONSchema.Validate(
gojsonschema.NewStringLoader(output))
suite.NoError(err)
suite.Empty(validated.Errors())
suite.True(validated.Valid())
suite.Contains(output, "10.11.12.13")
suite.Contains(output, "2001:db8:85a3::8a2e:370:7334")
suite.Contains(output, "ipv4")
suite.Contains(output, "ipv6")
suite.Contains(output, suite.cli.Access.Config.Secret.Base64())
suite.Contains(output, suite.cli.Access.Config.Secret.Hex())
}
func (suite *AccessTestSuite) TestIPv4CallFail() {
suite.NoError(
suite.cli.Access.Config.Network.PublicIP.IPv6.UnmarshalText(
[]byte("2001:0db8:85a3:0000:0000:8a2e:0370:7334")))
httpmock.RegisterResponder(http.MethodGet, "https://ifconfig.co",
httpmock.NewStringResponder(http.StatusForbidden, ""))
output := suite.CaptureStdout(func() {
suite.NoError(suite.cli.Access.Execute(suite.cli))
})
validated, err := accressResponseJSONSchema.Validate(
gojsonschema.NewStringLoader(output))
suite.NoError(err)
suite.Empty(validated.Errors())
suite.True(validated.Valid())
suite.Contains(output, "2001:db8:85a3::8a2e:370:7334")
suite.NotContains(output, "ipv4")
suite.Contains(output, "ipv6")
suite.Contains(output, suite.cli.Access.Config.Secret.Base64())
suite.Contains(output, suite.cli.Access.Config.Secret.Hex())
}
func TestAccess(t *testing.T) {
t.Parallel()
suite.Run(t, &AccessTestSuite{})
}
+4 -4
View File
@@ -11,8 +11,8 @@ import (
)
type base struct {
network network.Network
conf *config.Config
Network network.Network
Config *config.Config
}
func (b *base) ReadConfig(path, version string) error {
@@ -31,8 +31,8 @@ func (b *base) ReadConfig(path, version string) error {
return fmt.Errorf("cannot build a network: %w", err)
}
b.conf = conf
b.network = ntw
b.Config = conf
b.Network = ntw
return nil
}
+3 -3
View File
@@ -3,7 +3,7 @@ package cli
import "github.com/alecthomas/kong"
type CLI struct {
GenerateSecret GenerateSecret `cmd help:"Generate new proxy secret"` // nolint: govet
Access Access `cmd help:"Print access information."` // nolint: govet
Version kong.VersionFlag `help:"Print version."`
GenerateSecret GenerateSecret `kong:"cmd,help='Generate new proxy secret'"` // nolint: govet
Access Access `kong:"cmd,help='Print access information.'"` // nolint: govet
Version kong.VersionFlag `kong:"help='Print version.'"`
}
+3 -3
View File
@@ -7,10 +7,10 @@ import (
)
type GenerateSecret struct {
base
base `kong:"-"`
HostName string `arg optional help:"Hostname to use for domain fronting. Default is '${domain_front}'." name:"hostname" default:"${domain_front}"` // nolint: lll, govet
Hex bool `help:"Print secret in hex encoding."`
HostName string `kong:"arg,required,help='Hostname to use for domain fronting.',name='hostname'"` // nolint: lll, govet
Hex bool `kong:"help='Print secret in hex encoding.'"`
}
func (c *GenerateSecret) Run(cli *CLI, _ string) error {