github.com/Redstoneguy129/cli@v0.0.0-20230211220159-15dca4e91917/internal/restrictions/update/update.go (about)

     1  package update
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"net"
     8  
     9  	"github.com/spf13/afero"
    10  	"github.com/Redstoneguy129/cli/internal/utils"
    11  	"github.com/Redstoneguy129/cli/pkg/api"
    12  )
    13  
    14  func validateCidrs(cidrs []string, bypassChecks bool) error {
    15  	for _, cidr := range cidrs {
    16  		ip, _, err := net.ParseCIDR(cidr)
    17  		if err != nil {
    18  			return fmt.Errorf("failed to parse IP: %s", cidr)
    19  		}
    20  		if ip.IsPrivate() && !bypassChecks {
    21  			return fmt.Errorf("private IP provided: %s", cidr)
    22  		}
    23  		if ip.To4() == nil {
    24  			return fmt.Errorf("only IPv4 supported at the moment: %s", cidr)
    25  		}
    26  	}
    27  	return nil
    28  }
    29  
    30  func Run(ctx context.Context, projectRefArg string, dbCidrsToAllow []string, bypassCidrChecks bool, fsys afero.Fs) error {
    31  	// 1. Sanity checks.
    32  	projectRef := projectRefArg
    33  
    34  	// 1. sanity checks
    35  	{
    36  		if len(projectRefArg) == 0 {
    37  			ref, err := utils.LoadProjectRef(fsys)
    38  			if err != nil {
    39  				return err
    40  			}
    41  			projectRef = ref
    42  		} else if !utils.ProjectRefPattern.MatchString(projectRef) {
    43  			return errors.New("Invalid project ref format. Must be like `abcdefghijklmnopqrst`.")
    44  		}
    45  		err := validateCidrs(dbCidrsToAllow, bypassCidrChecks)
    46  		if err != nil {
    47  			return err
    48  		}
    49  	}
    50  
    51  	// 2. update restrictions
    52  	{
    53  		resp, err := utils.GetSupabase().ApplyNetworkRestrictionsWithResponse(ctx, projectRef, api.ApplyNetworkRestrictionsJSONRequestBody{
    54  			DbAllowedCidrs: dbCidrsToAllow,
    55  		})
    56  		if err != nil {
    57  			return err
    58  		}
    59  		if resp.JSON201 == nil {
    60  			return errors.New("failed to update network restrictions: " + string(resp.Body))
    61  		}
    62  		fmt.Printf("DB Allowed CIDRs: %+v\n", resp.JSON201.Config.DbAllowedCidrs)
    63  		fmt.Printf("Restrictions applied successfully: %+v\n", resp.JSON201.Status == "applied")
    64  		return nil
    65  	}
    66  }