pritunl

package module
v0.0.0-...-6307fb3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 27, 2024 License: MIT Imports: 15 Imported by: 0

README

pritunl-api-go

Pritunl API Client for Go

A Go client for the Pritunl API, allowing you to interact with Pritunl servers and perform various actions.

Quality Gate Status

Getting Started

Environment Variables

Load your Pritunl API credentials as environment variables:

export PRITUNL_BASE_URL="https://vpn.domain.tld"
export PRITUNL_API_TOKEN="<PRITUNL API TOKEN>"
export PRITUNL_API_SECRET="<PRITUNL API SECRET>"
Installation

Get the Pritunl API Client for Go package/library:

go get github.com/nathanielvarona/pritunl-api-go
Usage

Initialize an API instance and call available feature functions:

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/nathanielvarona/pritunl-api-go"
)

func main() {
	// Initialize the Pritunl API client
	client, err := pritunl.NewClient()
	// Alternatively, you can initialize the client with manual arguments
	// client, err := pritunl.NewClient(&pritunl.Client{
	// 	BaseUrl:   "<PRITUNL BASE URL>",
	// 	ApiToken:  "<PRITUNL API TOKEN>",
	// 	ApiSecret: "<PRITUNL API SECRET>",
	// })
	if err != nil {
		log.Fatal(err)
	}

	// Create a context for the request
	ctx := context.Background()

	// Retrieve the server status
	status, err := client.StatusGet(ctx)
	if err != nil {
		log.Fatal(err)
	}

	// Print server status details
	fmt.Println("Server Status:")
	for _, stat := range status {
		fmt.Println("Server Version:", stat.ServerVersion)
		fmt.Println("Local Networks:", stat.LocalNetworks)
		fmt.Println("Host Online:", stat.HostsOnline)
		fmt.Println("------")
	}

	// Marshal server status to JSON
	statusBytes, err := json.MarshalIndent(status, "", "  ")
	if err != nil {
		log.Println("Error marshalling status:", err)
	} else {
		fmt.Println("Server Status in JSON:")
		fmt.Println(string(statusBytes))
	}
}

Examples

Check the _examples folder for code examples demonstrating how to use this package/library.

Features

Core Pritunl API Client
Feature Function Description Status
StatusGet Status of Pritunl Server ✅ Yes
KeyGet Generate or Retrieve a Key for the User ✅ Yes
UserGet Get the Information of Existing User ✅ Yes
UserCreate Create a New User ✅ Yes
UserUpdate Update an Existing User ✅ Yes
UserDelete Delete an User ✅ Yes
OrganizationGet Get the Information of Existing Org ✅ Yes
OrganizationCreate Create a New Org ✅ Yes
OrganizationUpdate Update an Existing Org ✅ Yes
OrganizationDelete Delete an Org ✅ Yes
ServerGet Get the Information of Existing Server ✅ Yes
ServerCreate Create a New Server ✅ Yes
ServerUpdate Update an existing Server ✅ Yes
ServerDelete Delete a Server ✅ Yes
ServerRouteGet Get the Routes for a Server ✅ Yes
ServerRouteCreate Create/Add a Server Route ✅ Yes
ServerRouteUpdate Update a Server Route ✅ Yes
ServerRouteDelete Remove/Delete a Server Route ✅ Yes
ServerOrgAttach Attach an Organization for a Server ✅ Yes
ServerOrgDetach Detach an Organization for a Server ✅ Yes
ServerHostAttach Attach a Host for a Server ✅ Yes
ServerHostDetach Detach a Host for a Server ✅ Yes
Future Enhancements (CLI)
  1. CLI Framework: Consider using a popular framework like spf13/cobra, urfave/cli, or alecthomas/kong to simplify the command structure, argument parsing, and flag handling.
  2. Build Distribution Workflow: Implement a CI/CD workflow (e.g., using GitHub Actions) to automate building and distributing the CLI tool across various platforms (Windows, macOS, Linux) and architectures (32-bit, 64-bit). This will streamline setup for users on different systems.

Alternative API Clients

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	BaseUrl   string
	ApiToken  string
	ApiSecret string
}

Client represents a Pritunl API client

func NewClient

func NewClient(pritunl ...*Client) (*Client, error)

NewClient creates a new Pritunl client instance

func (*Client) AuthRequest

func (c *Client) AuthRequest(ctx context.Context, method, path string, data []byte) (*http.Response, error)

AuthRequest performs an authenticated API request

func (*Client) KeyGet

func (c *Client) KeyGet(ctx context.Context, orgId string, userId string) ([]KeyResponse, error)

KeyGet retrieves a key or keys on the server

func (*Client) OrganizationCreate

func (c *Client) OrganizationCreate(ctx context.Context, newOrganization OrganizationRequest) ([]OrganizationResponse, error)

OrganizationCreate creates a new organization on the server

func (*Client) OrganizationDelete

func (c *Client) OrganizationDelete(ctx context.Context, orgId string) ([]OrganizationResponse, error)

OrganizationDelete deletes an existing organization on the server

func (*Client) OrganizationGet

func (c *Client) OrganizationGet(ctx context.Context, orgId ...string) ([]OrganizationResponse, error)

OrganizationGet retrieves a organization or organizations on the server

func (*Client) OrganizationUpdate

func (c *Client) OrganizationUpdate(ctx context.Context, orgId string, updateOrganization OrganizationRequest) ([]OrganizationResponse, error)

OrganizationUpdate updates an existing organization on the server

func (*Client) ServerCreate

func (c *Client) ServerCreate(ctx context.Context, newServer ServerRequest) ([]ServerResponse, error)

ServerCreate creates a new server

func (*Client) ServerDelete

func (c *Client) ServerDelete(ctx context.Context, srvId string) ([]ServerResponse, error)

ServerDelete deletes an existing server

func (*Client) ServerGet

func (c *Client) ServerGet(ctx context.Context, srvId ...string) ([]ServerResponse, error)

ServerGet retrieves a server or servers

func (*Client) ServerHostAttach

func (c *Client) ServerHostAttach(ctx context.Context, srvId string, hostId string, newServerHost ServerHostRequest) ([]ServerHostResponse, error)

ServerHostAttach attaches a host to a server

func (*Client) ServerHostDetach

func (c *Client) ServerHostDetach(ctx context.Context, srvId string, hostId string) ([]ServerHostResponse, error)

ServerHostDetach detaches a host from a server

func (*Client) ServerOrgAttach

func (c *Client) ServerOrgAttach(ctx context.Context, srvId string, orgId string, newServerOrg ServerOrgRequest) ([]ServerOrgResponse, error)

ServerOrgAttach attaches an organization to a server

func (*Client) ServerOrgDetach

func (c *Client) ServerOrgDetach(ctx context.Context, srvId string, orgId string) ([]ServerOrgResponse, error)

ServerOrgDetach detaches an organization from a server

func (*Client) ServerRouteCreate

func (c *Client) ServerRouteCreate(ctx context.Context, srvId string, newServerRoute ServerRouteRequest) ([]ServerRouteResponse, error)

ServerRouteCreate adds a route to a network

func (*Client) ServerRouteDelete

func (c *Client) ServerRouteDelete(ctx context.Context, srvId string, routeId string) ([]ServerRouteResponse, error)

ServerRouteDelete removes a server route

func (*Client) ServerRouteGet

func (c *Client) ServerRouteGet(ctx context.Context, srvId string) ([]ServerRouteResponse, error)

ServerRouteGet retrieves the server routes

func (*Client) ServerRouteUpdate

func (c *Client) ServerRouteUpdate(ctx context.Context, srvId string, routeId string, newServerRoute ServerRouteRequest) ([]ServerRouteResponse, error)

ServerRouteUpdate updates a server route

func (*Client) ServerStart

func (c *Client) ServerStart(ctx context.Context, srvId string) ([]ServerResponse, error)

ServerStart starts an existing server

func (*Client) ServerStop

func (c *Client) ServerStop(ctx context.Context, srvId string) ([]ServerResponse, error)

ServerStop stops an existing server

func (*Client) ServerUpdate

func (c *Client) ServerUpdate(ctx context.Context, srvId string, newServer ServerRequest) ([]ServerResponse, error)

ServerUpdate updates an existing server

func (*Client) StatusGet

func (c *Client) StatusGet(ctx context.Context) ([]StatusResponse, error)

StatusGet retrieves the Pritunl server status

func (*Client) UserCreate

func (c *Client) UserCreate(ctx context.Context, orgId string, newUser UserRequest) ([]UserResponse, error)

UserCreate creates a new user on the server

func (*Client) UserDelete

func (c *Client) UserDelete(ctx context.Context, orgId string, userId string) ([]UserResponse, error)

UserDelete deletes an existing user on the server

func (*Client) UserGet

func (c *Client) UserGet(ctx context.Context, orgId string, userId ...string) ([]UserResponse, error)

UserGet retrieves a user or users on the server

func (*Client) UserUpdate

func (c *Client) UserUpdate(ctx context.Context, orgId string, userId string, updateUser UserRequest) ([]UserResponse, error)

UserUpdate updates an existing user on the server

type KeyResponse

type KeyResponse struct {
	ID        string `json:"id"`
	KeyURL    string `json:"key_url"`
	KeyZipURL string `json:"key_zip_url"`
	KeyOncURL string `json:"key_onc_url"`
	ViewURL   string `json:"view_url"`
	URIURL    string `json:"uri_url"`
}

KeyResponse represents a key response from the Pritunl API

type OrganizationRequest

type OrganizationRequest struct {
	Name       string `json:"name"`
	AuthApi    bool   `json:"auth_api"`
	AuthToken  bool   `json:"auth_token"`  // Addition for Put Method
	AuthSecret bool   `json:"auth_secret"` // Addition for Put Method
}

OrganizationRequest represents the structure of the organization request

type OrganizationResponse

type OrganizationResponse struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	AuthApi    bool   `json:"auth_api"`
	AuthToken  bool   `json:"auth_token"`
	AuthSecret bool   `json:"auth_secret"`
	UserCount  int    `json:"user_count"`
}

OrganizationResponse represents the structure of the organization response

type ServerData

type ServerData struct {
	ID             string      `json:"id"`
	Name           string      `json:"name"`
	Status         bool        `json:"status"`
	ServerID       string      `json:"server_id"`
	DeviceName     interface{} `json:"device_name"`
	Platform       interface{} `json:"platform"`
	RealAddress    interface{} `json:"real_address"`
	VirtAddress    string      `json:"virt_address"`
	VirtAddress6   string      `json:"virt_address6"`
	ConnectedSince interface{} `json:"connected_since"`
}

Substructure of `UserResponse` struct for `Servers` field

type ServerHostRequest

type ServerHostRequest struct {
	ID      string `json:"id"`
	Server  string `json:"server"`
	Name    string `json:"name"`
	Address string `json:"address"`
}

ServerHostRequest represents a request to attach or detach a host to a server

type ServerHostResponse

type ServerHostResponse struct {
	ID      string `json:"id"`
	Server  string `json:"server"`
	Status  string `json:"status"`
	Name    string `json:"name"`
	Address string `json:"address"`
}

ServerHostResponse represents a server host response

type ServerOrgRequest

type ServerOrgRequest struct {
	ID     string `json:"id"`
	Server string `json:"server"`
	Name   string `json:"name"`
}

ServerOrgRequest represents a request to attach or detach an organization to a server

type ServerOrgResponse

type ServerOrgResponse struct {
	ID     string `json:"id"`
	Server string `json:"server"`
	Name   string `json:"name"`
}

ServerOrgResponse represents a server organization response

type ServerRequest

type ServerRequest struct {
	Name             string      `json:"name"`
	Network          string      `json:"network"`
	NetworkWg        string      `json:"network_wg"`
	NetworkMode      string      `json:"network_mode"`
	NetworkStart     *string     `json:"network_start,omitempty"`
	NetworkEnd       *string     `json:"network_end,omitempty"`
	RestrictRoutes   bool        `json:"restrict_routes"`
	Wg               bool        `json:"wg"`
	Ipv6             bool        `json:"ipv6"`
	Ipv6Firewall     bool        `json:"ipv6_firewall"`
	DynamicFirewall  bool        `json:"dynamic_firewall"`
	DeviceAuth       bool        `json:"device_auth"`
	BindAddress      *string     `json:"bind_address,omitempty"`
	Protocol         string      `json:"protocol"`
	Port             int         `json:"port"`
	PortWg           int         `json:"port_wg"`
	DhParamBits      int         `json:"dh_param_bits"`
	Groups           []string    `json:"groups"`
	MultiDevice      bool        `json:"multi_device"`
	DnsServers       []string    `json:"dns_servers"`
	SearchDomain     string      `json:"search_domain"`
	InterClient      bool        `json:"inter_client"`
	PingInterval     int         `json:"ping_interval"`
	PingTimeout      int         `json:"ping_timeout"`
	LinkPingInterval int         `json:"link_ping_interval"`
	LinkPingTimeout  int         `json:"link_ping_timeout"`
	InactiveTimeout  *int        `json:"inactive_timeout,omitempty"`
	SessionTimeout   *int        `json:"session_timeout,omitempty"`
	AllowedDevices   *string     `json:"allowed_devices,omitempty"`
	MaxClients       int         `json:"max_clients"`
	MaxDevices       int         `json:"max_devices"`
	ReplicaCount     int         `json:"replica_count"`
	Vxlan            bool        `json:"vxlan"`
	DnsMapping       bool        `json:"dns_mapping"`
	RouteDns         bool        `json:"route_dns"`
	Debug            bool        `json:"debug"`
	SsoAuth          bool        `json:"sso_auth"`
	OtpAuth          bool        `json:"otp_auth"`
	LzoCompression   bool        `json:"lzo_compression"`
	Cipher           string      `json:"cipher"`
	Hash             string      `json:"hash"`
	BlockOutsideDns  bool        `json:"block_outside_dns"`
	JumboFrames      bool        `json:"jumbo_frames"`
	PreConnectMsg    string      `json:"pre_connect_msg"`
	Policy           string      `json:"policy"`
	MssFix           interface{} `json:"mss_fix"`
	Multihome        bool        `json:"multihome"`
}

ServerRequest represents a request to create or update a server

type ServerResponse

type ServerResponse struct {
	ID               string      `json:"id"`
	Status           string      `json:"status"`
	Uptime           uint        `json:"uptime"`
	UsersOnline      int         `json:"users_online"`
	DevicesOnline    int         `json:"devices_online"`
	UserCount        int         `json:"user_count"`
	Name             string      `json:"name"` // Starting here is common to `ServerRequest` Struct
	Network          string      `json:"network"`
	NetworkWg        string      `json:"network_wg"`
	NetworkMode      string      `json:"network_mode"`
	NetworkStart     string      `json:"network_start"`
	NetworkEnd       string      `json:"network_end"`
	RestrictRoutes   bool        `json:"restrict_routes"`
	Wg               bool        `json:"wg"`
	Ipv6             bool        `json:"ipv6"`
	Ipv6Firewall     bool        `json:"ipv6_firewall"`
	DynamicFirewall  bool        `json:"dynamic_firewall"`
	DeviceAuth       bool        `json:"device_auth"`
	BindAddress      string      `json:"bind_address"`
	Protocol         string      `json:"protocol"`
	Port             int         `json:"port"`
	PortWg           int         `json:"port_wg"`
	DhParamBits      int         `json:"dh_param_bits"`
	Groups           []string    `json:"groups"`
	MultiDevice      bool        `json:"multi_device"`
	DnsServers       []string    `json:"dns_servers"`
	SearchDomain     string      `json:"search_domain"`
	InterClient      bool        `json:"inter_client"`
	PingInterval     int         `json:"ping_interval"`
	PingTimeout      int         `json:"ping_timeout"`
	LinkPingInterval int         `json:"link_ping_interval"`
	LinkPingTimeout  int         `json:"link_ping_timeout"`
	InactiveTimeout  int         `json:"inactive_timeout"`
	SessionTimeout   int         `json:"session_timeout"`
	AllowedDevices   string      `json:"allowed_devices"`
	MaxClients       int         `json:"max_clients"`
	MaxDevices       int         `json:"max_devices"`
	ReplicaCount     int         `json:"replica_count"`
	Vxlan            bool        `json:"vxlan"`
	DnsMapping       bool        `json:"dns_mapping"`
	RouteDns         bool        `json:"route_dns"`
	Debug            bool        `json:"debug"`
	SsoAuth          bool        `json:"sso_auth"`
	OtpAuth          bool        `json:"otp_auth"`
	LzoCompression   bool        `json:"lzo_compression"`
	Cipher           string      `json:"cipher"`
	Hash             string      `json:"hash"`
	BlockOutsideDns  bool        `json:"block_outside_dns"`
	JumboFrames      bool        `json:"jumbo_frames"`
	PreConnectMsg    string      `json:"pre_connect_msg"`
	Policy           string      `json:"policy"`
	MssFix           interface{} `json:"mss_fix"`
	Multihome        bool        `json:"multihome"`
}

ServerResponse represents a server response

type ServerRouteRequest

type ServerRouteRequest struct {
	ID                 string `json:"id"`
	Server             string `json:"server"`
	Network            string `json:"network"`
	Comment            string `json:"comment"`
	Metric             int    `json:"metric"`
	Nat                bool   `json:"nat"`
	NatInterface       string `json:"nat_interface"`
	NatNetmap          string `json:"nat_netmap"`
	Advertise          bool   `json:"advertise"`
	VpcRegion          string `json:"vpc_region"`
	VpcId              string `json:"vpc_id"`
	NetGateway         bool   `json:"net_gateway"`
	VirtualNetwork     bool   `json:"virtual_network"`
	NetworkLink        bool   `json:"network_link"`
	ServerLink         bool   `json:"server_link"` // Addition for Put Method
	LinkVirtualNetwork bool   `json:"link_virtual_network"`
	WgNetwork          bool   `json:"wg_network"`
}

ServerRouteRequest represents a request to create or update a server route

type ServerRouteResponse

type ServerRouteResponse struct {
	ID           string `json:"id"`
	Server       string `json:"server"`
	Network      string `json:"network"`
	Comment      string `json:"comment"`
	Metric       int    `json:"metric"`
	Nat          bool   `json:"nat"`
	NatInterface string `json:"nat_interface"`
	NatNetmap    string `json:"nat_netmap"`
	Advertise    bool   `json:"advertise"`
	VpcRegion    string `json:"vpc_region"`
	VpcId        string `json:"vpc_id"`
	NetGateway   bool   `json:"net_gateway"`
}

ServerRouteResponse represents a server route response

type StatusResponse

type StatusResponse struct {
	OrgCount      int      `json:"org_count"`
	UsersOnline   int      `json:"users_online"`
	UserCount     int      `json:"user_count"`
	ServersOnline int      `json:"servers_online"`
	ServerCount   int      `json:"server_count"`
	HostsOnline   int      `json:"hosts_online"`
	HostCount     int      `json:"host_count"`
	ServerVersion string   `json:"server_version"`
	CurrentHost   string   `json:"current_host"`
	PublicIP      string   `json:"public_ip"`
	LocalNetworks []string `json:"local_networks"`
	Notification  string   `json:"notification"`
}

StatusResponse represents the structure of Pritunl's status response

type UserPortForwardingData

type UserPortForwardingData struct {
	Protocol string `json:"protocol"`
	Port     string `json:"port"`
	Dport    string `json:"dport"`
}

Substructure of `UserRequest` and `UserResponse` structs for `PortForwarding` field

type UserRequest

type UserRequest struct {
	Name            string                   `json:"name"`
	Email           string                   `json:"email"`
	AuthType        string                   `json:"auth_type"`
	YubicoId        string                   `json:"yubico_id"`
	Groups          []string                 `json:"groups"`
	Pin             string                   `json:"pin"`
	Disabled        bool                     `json:"disabled"`
	NetworkLinks    []string                 `json:"network_links"`
	BypassSecondary bool                     `json:"bypass_secondary"`
	ClientToClient  bool                     `json:"client_to_client"`
	MacAddresses    []string                 `json:"mac_addresses"`
	DnsServers      []string                 `json:"dns_servers"`
	DnsSuffix       string                   `json:"dns_suffix"`
	PortForwarding  []UserPortForwardingData `json:"port_forwarding"`
	SendKeyEmail    bool                     `json:"send_key_email"` // Addition for Put Method
}

UserRequest represents the structure of User Get/Post/Put request

type UserResponse

type UserResponse struct {
	ID               string                   `json:"id"`
	Organization     string                   `json:"organization"`
	OrganizationName string                   `json:"organization_name"`
	Name             string                   `json:"name"`
	Email            string                   `json:"email"`
	Groups           []string                 `json:"groups"`
	LastActive       int64                    `json:"last_active"`
	Pin              bool                     `json:"pin"`
	Type             string                   `json:"type"`
	AuthType         string                   `json:"auth_type"`
	YubicoId         string                   `json:"yubico_id"`
	OTPSecret        string                   `json:"otp_secret"`
	Disabled         bool                     `json:"disabled"`
	BypassSecondary  bool                     `json:"bypass_secondary"`
	ClientToClient   bool                     `json:"client_to_client"`
	MacAddresses     []string                 `json:"mac_addresses"`
	DnsServers       []string                 `json:"dns_servers"`
	DnsSuffix        string                   `json:"dns_suffix"`
	PortForwarding   []UserPortForwardingData `json:"port_forwarding"`
	Devices          []interface{}            `json:"devices"`
	Gravatar         bool                     `json:"gravatar"`
	Audit            bool                     `json:"audit"`
	Status           bool                     `json:"status"`
	SSO              interface{}              `json:"sso"`
	AuthModes        []interface{}            `json:"auth_modes"`
	DNSMapping       interface{}              `json:"dns_mapping"`
	NetworkLinks     []interface{}            `json:"network_links"`
	Servers          []ServerData             `json:"servers"` // Nested struct for servers
}

UserResponse represents the structure of User response

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL