Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tests #84

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 35 additions & 20 deletions controllers/cloudflare_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,25 @@ import (
"encoding/json"
"fmt"

"github.com/cloudflare/cloudflare-go"
cf "github.com/cloudflare/cloudflare-go"
"github.com/go-logr/logr"
)

type CloudflareGoAPI interface {
CreateTunnel(ctx context.Context, rc *cf.ResourceContainer, params cf.TunnelCreateParams) (cf.Tunnel, error)
CleanupTunnelConnections(ctx context.Context, rc *cf.ResourceContainer, tunnelID string) error
DeleteTunnel(ctx context.Context, rc *cf.ResourceContainer, tunnelID string) error
Account(ctx context.Context, accountID string) (cf.Account, cf.ResultInfo, error)
Accounts(ctx context.Context, params cf.AccountsListParams) ([]cf.Account, cf.ResultInfo, error)
GetTunnel(ctx context.Context, rc *cf.ResourceContainer, tunnelID string) (cf.Tunnel, error)
ListTunnels(ctx context.Context, rc *cf.ResourceContainer, params cf.TunnelListParams) ([]cf.Tunnel, *cf.ResultInfo, error)
ListZones(ctx context.Context, z ...string) ([]cf.Zone, error)
UpdateDNSRecord(ctx context.Context, rc *cf.ResourceContainer, params cf.UpdateDNSRecordParams) error
CreateDNSRecord(ctx context.Context, rc *cf.ResourceContainer, params cf.CreateDNSRecordParams) (*cf.DNSRecordResponse, error)
DeleteDNSRecord(ctx context.Context, rc *cf.ResourceContainer, recordID string) error
ListDNSRecords(ctx context.Context, rc *cf.ResourceContainer, params cf.ListDNSRecordsParams) ([]cf.DNSRecord, *cf.ResultInfo, error)
}

// TXT_PREFIX is the prefix added to TXT records for whom the corresponding DNS records are managed by the operator.
const TXT_PREFIX = "_managed."

Expand All @@ -29,7 +44,7 @@ type CloudflareAPI struct {
ValidTunnelId string
ValidTunnelName string
ValidZoneId string
CloudflareClient *cloudflare.API
CloudflareClient CloudflareGoAPI
}

// CloudflareTunnelCredentialsFile object containing the fields that make up a Cloudflare Tunnel's credentials
Expand Down Expand Up @@ -61,15 +76,15 @@ func (c *CloudflareAPI) CreateCloudflareTunnel() (string, string, error) {
}
tunnelSecret := base64.StdEncoding.EncodeToString(randSecret)

params := cloudflare.TunnelCreateParams{
params := cf.TunnelCreateParams{
Name: c.TunnelName,
Secret: tunnelSecret,
// Indicates if this is a locally or remotely configured tunnel "local" or "cloudflare"
ConfigSrc: "local",
}

ctx := context.Background()
rc := cloudflare.AccountIdentifier(c.ValidAccountId)
rc := cf.AccountIdentifier(c.ValidAccountId)
tunnel, err := c.CloudflareClient.CreateTunnel(ctx, rc, params)

if err != nil {
Expand Down Expand Up @@ -100,7 +115,7 @@ func (c *CloudflareAPI) DeleteCloudflareTunnel() error {
}

ctx := context.Background()
rc := cloudflare.AccountIdentifier(c.ValidAccountId)
rc := cf.AccountIdentifier(c.ValidAccountId)

// Deletes any inactive connections on a tunnel
err := c.CloudflareClient.CleanupTunnelConnections(ctx, rc, c.ValidTunnelId)
Expand Down Expand Up @@ -182,7 +197,7 @@ func (c CloudflareAPI) validateAccountId() bool {

func (c *CloudflareAPI) getAccountIdByName() (string, error) {
ctx := context.Background()
params := cloudflare.AccountsListParams{
params := cf.AccountsListParams{
Name: c.AccountName,
}
accounts, _, err := c.CloudflareClient.Accounts(ctx, params)
Expand Down Expand Up @@ -245,7 +260,7 @@ func (c *CloudflareAPI) validateTunnelId() bool {
}

ctx := context.Background()
rc := cloudflare.AccountIdentifier(c.ValidAccountId)
rc := cf.AccountIdentifier(c.ValidAccountId)
tunnel, err := c.CloudflareClient.GetTunnel(ctx, rc, c.TunnelId)
if err != nil {
c.Log.Error(err, "error retrieving tunnel", "tunnelId", c.TunnelId)
Expand All @@ -263,8 +278,8 @@ func (c *CloudflareAPI) getTunnelIdByName() (string, error) {
}

ctx := context.Background()
rc := cloudflare.AccountIdentifier(c.ValidAccountId)
params := cloudflare.TunnelListParams{
rc := cf.AccountIdentifier(c.ValidAccountId)
params := cf.TunnelListParams{
Name: c.TunnelName,
}
tunnels, _, err := c.CloudflareClient.ListTunnels(ctx, rc, params)
Expand Down Expand Up @@ -362,10 +377,10 @@ func ptr[T any](v T) *T {
// InsertOrUpdateCName upsert DNS CNAME record for the given FQDN to point to the tunnel
func (c *CloudflareAPI) InsertOrUpdateCName(fqdn, dnsId string) (string, error) {
ctx := context.Background()
rc := cloudflare.ZoneIdentifier(c.ValidZoneId)
rc := cf.ZoneIdentifier(c.ValidZoneId)
if dnsId != "" {
c.Log.Info("Updating existing record", "fqdn", fqdn, "dnsId", dnsId)
updateParams := cloudflare.UpdateDNSRecordParams{
updateParams := cf.UpdateDNSRecordParams{
ID: dnsId,
Type: "CNAME",
Name: fqdn,
Expand All @@ -383,7 +398,7 @@ func (c *CloudflareAPI) InsertOrUpdateCName(fqdn, dnsId string) (string, error)
return dnsId, nil
} else {
c.Log.Info("Inserting DNS record", "fqdn", fqdn)
createParams := cloudflare.CreateDNSRecordParams{
createParams := cf.CreateDNSRecordParams{
Type: "CNAME",
Name: fqdn,
Content: fmt.Sprintf("%s.cfargotunnel.com", c.ValidTunnelId),
Expand All @@ -409,7 +424,7 @@ func (c *CloudflareAPI) DeleteDNSId(fqdn, dnsId string, created bool) error {
}

ctx := context.Background()
rc := cloudflare.ZoneIdentifier(c.ValidZoneId)
rc := cf.ZoneIdentifier(c.ValidZoneId)
err := c.CloudflareClient.DeleteDNSRecord(ctx, rc, dnsId)

if err != nil {
Expand All @@ -428,8 +443,8 @@ func (c *CloudflareAPI) GetDNSCNameId(fqdn string) (string, error) {
}

ctx := context.Background()
rc := cloudflare.ZoneIdentifier(c.ValidZoneId)
params := cloudflare.ListDNSRecordsParams{
rc := cf.ZoneIdentifier(c.ValidZoneId)
params := cf.ListDNSRecordsParams{
Type: "CNAME",
Name: fqdn,
}
Expand Down Expand Up @@ -461,8 +476,8 @@ func (c *CloudflareAPI) GetManagedDnsTxt(fqdn string) (string, DnsManagedRecordT
}

ctx := context.Background()
rc := cloudflare.ZoneIdentifier(c.ValidZoneId)
params := cloudflare.ListDNSRecordsParams{
rc := cf.ZoneIdentifier(c.ValidZoneId)
params := cf.ListDNSRecordsParams{
Type: "TXT",
Name: fmt.Sprintf("%s%s", TXT_PREFIX, fqdn),
}
Expand Down Expand Up @@ -506,12 +521,12 @@ func (c *CloudflareAPI) InsertOrUpdateTXT(fqdn, txtId, dnsId string) error {
return err
}
ctx := context.Background()
rc := cloudflare.ZoneIdentifier(c.ValidZoneId)
rc := cf.ZoneIdentifier(c.ValidZoneId)

if txtId != "" {
c.Log.Info("Updating existing TXT record", "fqdn", fqdn, "dnsId", dnsId, "txtId", txtId)

updateParams := cloudflare.UpdateDNSRecordParams{
updateParams := cf.UpdateDNSRecordParams{
ID: txtId,
Type: "TXT",
Name: fmt.Sprintf("%s%s", TXT_PREFIX, fqdn),
Expand All @@ -529,7 +544,7 @@ func (c *CloudflareAPI) InsertOrUpdateTXT(fqdn, txtId, dnsId string) error {
return nil
} else {
c.Log.Info("Inserting DNS TXT record", "fqdn", fqdn)
createParams := cloudflare.CreateDNSRecordParams{
createParams := cf.CreateDNSRecordParams{
Type: "TXT",
Name: fmt.Sprintf("%s%s", TXT_PREFIX, fqdn),
Content: string(content),
Expand Down
204 changes: 204 additions & 0 deletions controllers/cloudflare_api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
package controllers_test

import (
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"time"

"github.com/adyanth/cloudflare-operator/controllers"
cf "github.com/cloudflare/cloudflare-go"
"github.com/go-logr/logr/testr"
"github.com/stretchr/testify/assert"
)

type credfile struct {
AccountTag string
TunnelID string
TunnelName string
TunnelSecret string
}

type cfGoClient struct {
accountID string
accountName string
tunnelName string
tunnelID string
tunnelSecret string
domain string
records map[string]cf.DNSRecord
err error

cleanedUp bool
deleted bool
}

func (c *cfGoClient) CreateTunnel(ctx context.Context, rc *cf.ResourceContainer, params cf.TunnelCreateParams) (cf.Tunnel, error) {
if params.Name != c.tunnelName {
return cf.Tunnel{}, fmt.Errorf("Invalid tunnel name")
}
now := time.Now()
c.tunnelSecret = params.Secret
return cf.Tunnel{
ID: c.tunnelID,
Name: c.tunnelName,
Secret: params.Secret,
CreatedAt: &now,
RemoteConfig: false,
}, c.err
}

func (c *cfGoClient) CleanupTunnelConnections(ctx context.Context, rc *cf.ResourceContainer, tunnelID string) error {
c.cleanedUp = true
return c.err
}

func (c *cfGoClient) DeleteTunnel(ctx context.Context, rc *cf.ResourceContainer, tunnelID string) error {
c.deleted = true
return c.err
}

func (c *cfGoClient) Account(ctx context.Context, accountID string) (cf.Account, cf.ResultInfo, error) {
return cf.Account{
ID: c.accountID,
Name: c.accountName,
Type: "",
CreatedOn: time.Now(),
}, cf.ResultInfo{}, c.err
}

func (c *cfGoClient) Accounts(ctx context.Context, params cf.AccountsListParams) ([]cf.Account, cf.ResultInfo, error) {
if params.Name == c.accountName {
return []cf.Account{{
ID: c.accountID,
Name: c.accountName,
Type: "",
CreatedOn: time.Now(),
}}, cf.ResultInfo{}, c.err
}
return []cf.Account{}, cf.ResultInfo{}, fmt.Errorf("No such account ID")
}

func (c *cfGoClient) GetTunnel(ctx context.Context, rc *cf.ResourceContainer, tunnelID string) (cf.Tunnel, error) {
now := time.Now()
return cf.Tunnel{
ID: c.tunnelID,
Name: c.tunnelName,
Secret: c.tunnelSecret,
CreatedAt: &now,
RemoteConfig: false,
}, c.err
}

func (c *cfGoClient) ListTunnels(ctx context.Context, rc *cf.ResourceContainer, params cf.TunnelListParams) ([]cf.Tunnel, *cf.ResultInfo, error) {
if params.Name == c.tunnelName {
now := time.Now()
return []cf.Tunnel{{
ID: c.tunnelID,
Name: c.tunnelName,
Secret: c.tunnelSecret,
CreatedAt: &now,
RemoteConfig: false,
}}, &cf.ResultInfo{}, c.err
}
return []cf.Tunnel{}, &cf.ResultInfo{}, fmt.Errorf("No such tunnel")
}

func (c *cfGoClient) ListZones(ctx context.Context, z ...string) ([]cf.Zone, error) {
if strings.HasSuffix(z[0], c.domain) {
return []cf.Zone{{
ID: "zone-id",
Name: "zone-name",
}}, c.err
}
return []cf.Zone{}, fmt.Errorf("No such zone")
}

func (c *cfGoClient) UpdateDNSRecord(ctx context.Context, rc *cf.ResourceContainer, params cf.UpdateDNSRecordParams) error {
if rec, ok := c.records[params.ID]; ok && (params.Name == "" || params.Name == rec.Name) && params.Type == rec.Type {
rec.Content = params.Content
c.records[params.ID] = rec
return c.err
}
return fmt.Errorf("Error updating DNS")
}

func (c *cfGoClient) CreateDNSRecord(ctx context.Context, rc *cf.ResourceContainer, params cf.CreateDNSRecordParams) (*cf.DNSRecordResponse, error) {
id := fmt.Sprint(len(c.records))
c.records[id] = cf.DNSRecord{
ID: id,
Type: params.Type,
Name: params.Name,
Content: params.Content,
}
return &cf.DNSRecordResponse{
Result: c.records[id],
}, c.err
}

func (c *cfGoClient) DeleteDNSRecord(ctx context.Context, rc *cf.ResourceContainer, recordID string) error {
if _, ok := c.records[recordID]; ok {
delete(c.records, recordID)
return c.err
}
return fmt.Errorf("no record to delete")
}

func (c *cfGoClient) ListDNSRecords(ctx context.Context, rc *cf.ResourceContainer, params cf.ListDNSRecordsParams) ([]cf.DNSRecord, *cf.ResultInfo, error) {
recs := []cf.DNSRecord{}
for _, v := range c.records {
if params.Type == v.Type && (params.Name == v.Name || params.Content == v.Comment) {
recs = append(recs, v)
}
}
return recs, &cf.ResultInfo{}, c.err
}

func setup(t *testing.T) (*controllers.CloudflareAPI, *cfGoClient) {
cc := cfGoClient{
accountName: "account-name",
accountID: "account-id",
tunnelName: "tunnel-name",
tunnelID: "tunnel-id",
tunnelSecret: "secret",
domain: "domain",
err: nil,
}
return &controllers.CloudflareAPI{
Log: testr.New(t),
TunnelName: cc.tunnelName,
TunnelId: cc.tunnelID,
AccountName: cc.accountName,
AccountId: cc.accountID,
Domain: cc.domain,
APIToken: "api-token",
APIKey: "api-key",
APIEmail: "api-email",
CloudflareClient: &cc,
}, &cc
}

func TestCreateCloudflareTunnel(t *testing.T) {
c, cc := setup(t)
id, creds, err := c.CreateCloudflareTunnel()
if assert.NoError(t, err, "expected no error") {
assert.Equal(t, c.TunnelId, id)
v := credfile{}
if assert.NoError(t, json.Unmarshal([]byte(creds), &v)) {
assert.Equal(t, cc.accountID, v.AccountTag)
assert.Equal(t, cc.tunnelID, v.TunnelID)
assert.Equal(t, cc.tunnelName, v.TunnelName)
assert.Equal(t, cc.tunnelSecret, v.TunnelSecret)
}
}
}

func TestDeleteCloudflareTunnel(t *testing.T) {
c, cc := setup(t)
err := c.DeleteCloudflareTunnel()
if assert.NoError(t, err, "expected no error") {
assert.Equal(t, true, cc.deleted)
}
}
Loading