/*
Copyright (c) 2018 VMware, Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package sts

import (
	"crypto/tls"
	"net/http"
	"strings"
	"testing"

	"github.com/vmware/govmomi/session"
	"github.com/vmware/govmomi/vim25/methods"
	"github.com/vmware/govmomi/vim25/soap"
	"github.com/vmware/govmomi/vim25/types"
	"github.com/vmware/govmomi/vim25/xml"
)

var _ soap.Signer = new(Signer)

// LocalhostCert copied from go/src/net/http/internal/testcert.go
var LocalhostCert = []byte(`-----BEGIN CERTIFICATE-----
MIICEzCCAXygAwIBAgIQMIMChMLGrR+QvmQvpwAU6zANBgkqhkiG9w0BAQsFADAS
MRAwDgYDVQQKEwdBY21lIENvMCAXDTcwMDEwMTAwMDAwMFoYDzIwODQwMTI5MTYw
MDAwWjASMRAwDgYDVQQKEwdBY21lIENvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB
iQKBgQDuLnQAI3mDgey3VBzWnB2L39JUU4txjeVE6myuDqkM/uGlfjb9SjY1bIw4
iA5sBBZzHi3z0h1YV8QPuxEbi4nW91IJm2gsvvZhIrCHS3l6afab4pZBl2+XsDul
rKBxKKtD1rGxlG4LjncdabFn9gvLZad2bSysqz/qTAUStTvqJQIDAQABo2gwZjAO
BgNVHQ8BAf8EBAMCAqQwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUw
AwEB/zAuBgNVHREEJzAlggtleGFtcGxlLmNvbYcEfwAAAYcQAAAAAAAAAAAAAAAA
AAAAATANBgkqhkiG9w0BAQsFAAOBgQCEcetwO59EWk7WiJsG4x8SY+UIAA+flUI9
tyC4lNhbcF2Idq9greZwbYCqTTTr2XiRNSMLCOjKyI7ukPoPjo16ocHj+P3vZGfs
h1fIw3cSS2OolhloGw/XM6RWPWtPAlGykKLciQrBru5NAPvCMsb/I1DAceTiotQM
fblo6RBxUQ==
-----END CERTIFICATE-----`)

// LocalhostKey copied from go/src/net/http/internal/testcert.go
var LocalhostKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDuLnQAI3mDgey3VBzWnB2L39JUU4txjeVE6myuDqkM/uGlfjb9
SjY1bIw4iA5sBBZzHi3z0h1YV8QPuxEbi4nW91IJm2gsvvZhIrCHS3l6afab4pZB
l2+XsDulrKBxKKtD1rGxlG4LjncdabFn9gvLZad2bSysqz/qTAUStTvqJQIDAQAB
AoGAGRzwwir7XvBOAy5tM/uV6e+Zf6anZzus1s1Y1ClbjbE6HXbnWWF/wbZGOpet
3Zm4vD6MXc7jpTLryzTQIvVdfQbRc6+MUVeLKwZatTXtdZrhu+Jk7hx0nTPy8Jcb
uJqFk541aEw+mMogY/xEcfbWd6IOkp+4xqjlFLBEDytgbIECQQDvH/E6nk+hgN4H
qzzVtxxr397vWrjrIgPbJpQvBsafG7b0dA4AFjwVbFLmQcj2PprIMmPcQrooz8vp
jy4SHEg1AkEA/v13/5M47K9vCxmb8QeD/asydfsgS5TeuNi8DoUBEmiSJwma7FXY
fFUtxuvL7XvjwjN5B30pNEbc6Iuyt7y4MQJBAIt21su4b3sjXNueLKH85Q+phy2U
fQtuUE9txblTu14q3N7gHRZB4ZMhFYyDy8CKrN2cPg/Fvyt0Xlp/DoCzjA0CQQDU
y2ptGsuSmgUtWj3NM9xuwYPm+Z/F84K6+ARYiZ6PYj013sovGKUFfYAqVXVlxtIX
qyUBnu3X9ps8ZfjLZO7BAkEAlT4R5Yl6cGhaJQYZHOde3JEMhNRcVFMO8dJDaFeo
f9Oeos0UUothgiDktdQHxdNEwLjQf7lJJBzV+5OtwswCWA==
-----END RSA PRIVATE KEY-----`)

func TestSigner(t *testing.T) {
	cert, err := tls.X509KeyPair(LocalhostCert, LocalhostKey)
	if err != nil {
		t.Fatal(err)
	}

	s := &Signer{}

	env := soap.Envelope{
		Header: new(soap.Header),
		Body: &methods.LoginByTokenBody{
			Req: &types.LoginByToken{
				This: types.ManagedObjectReference{
					Type:  "SessionManager",
					Value: "SessionManager",
				},
				Locale: session.Locale,
			},
		},
	}

	_, err = s.Sign(env)
	if err != nil {
		t.Error(err)
	}

	s.Certificate = &cert

	_, err = s.Sign(env)
	if err == nil {
		t.Error("expected error")
	}

	// Sign() just needs to parse the Assertion.ID
	s.Token = `<saml2:Assertion ID="tokenID"></saml2:Assertion>`

	b, err := s.Sign(env)
	if err != nil {
		t.Error(err)
	}

	// TODO: new(internal.Security) would require more use of xml.Name instead of field tags
	security := struct {
		InnerXML string `xml:",innerxml"`
	}{}

	senv := soap.Envelope{
		Header: &soap.Header{
			Security: &security,
		},
	}
	err = xml.Unmarshal(b, &senv)
	if err != nil {
		t.Fatal(err)
	}

	if !strings.HasPrefix(security.InnerXML, "<wsu:Timestamp ") {
		t.Error("missing timestamp")
	}

	if !strings.HasSuffix(security.InnerXML, "</ds:Signature>") {
		t.Error("missing signature")
	}

	req, _ := http.NewRequest(http.MethodPost, "https://127.0.0.1", nil)
	err = s.SignRequest(req)
	if err != nil {
		t.Fatal(err)
	}

	req, _ = http.NewRequest(http.MethodPost, "https://[0:0:0:0:0:0:0:1]", nil)
	err = s.SignRequest(req)
	if err != nil {
		t.Fatal(err)
	}
}

func TestIsIPv6(t *testing.T) {
	tests := []struct {
		ip string
		v6 bool
	}{
		{"0:0:0:0:0:0:0:1", true},
		{"10.0.0.42", false},
	}

	for _, test := range tests {
		v6 := isIPv6(test.ip)
		if v6 != test.v6 {
			t.Errorf("%s: expected %t, got %t", test.ip, test.v6, v6)
		}
	}
}
