github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/client/doc_test.go (about)

     1  // Copyright 2021 Gravitational, Inc
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package client_test
    16  
    17  // this package adds godoc examples for several Client types and functions
    18  // See https://pkg.go.dev/github.com/fluhus/godoc-tricks#Examples
    19  
    20  import (
    21  	"context"
    22  	"fmt"
    23  	"log"
    24  	"os"
    25  	"time"
    26  
    27  	"github.com/gravitational/teleport/api/client"
    28  	"github.com/gravitational/teleport/api/types"
    29  )
    30  
    31  // Below is an example of creating a new Teleport Auth client with Profile credentials,
    32  // and using that client to create, get, and delete a Role resource object.
    33  //
    34  // Make sure to look at the Getting Started guide before attempting to run this example.
    35  func ExampleClient_roleCRUD() {
    36  	ctx := context.Background()
    37  
    38  	// Create a new client in your go file.
    39  	clt, err := client.New(ctx, client.Config{
    40  		Credentials: []client.Credentials{
    41  			client.LoadProfile("", ""),
    42  		},
    43  		// set to true if your Teleport web proxy doesn't have HTTP/TLS certificate
    44  		// configured yet (never use this in production).
    45  		InsecureAddressDiscovery: false,
    46  	})
    47  	if err != nil {
    48  		log.Fatalf("failed to create client: %v", err)
    49  	}
    50  	defer clt.Close()
    51  
    52  	// Resource Spec structs reflect their Resource's yaml definition.
    53  	roleSpec := types.RoleSpecV6{
    54  		Options: types.RoleOptions{
    55  			MaxSessionTTL: types.Duration(time.Hour),
    56  		},
    57  		Allow: types.RoleConditions{
    58  			Logins: []string{"role1"},
    59  			Rules: []types.Rule{
    60  				types.NewRule(types.KindAccessRequest, []string{types.VerbList, types.VerbRead}),
    61  			},
    62  		},
    63  		Deny: types.RoleConditions{
    64  			NodeLabels: types.Labels{"*": []string{"*"}},
    65  		},
    66  	}
    67  
    68  	// There are helper functions for creating Teleport resources.
    69  	role, err := types.NewRole("role1", roleSpec)
    70  	if err != nil {
    71  		log.Fatalf("failed to get role: %v", err)
    72  	}
    73  
    74  	// Getters and setters can be used to alter specs.
    75  	role.SetLogins(types.Allow, []string{"root"})
    76  
    77  	// Upsert overwrites the resource if it exists. Use this to create/update resources.
    78  	// Equivalent to `tctl create -f role1.yaml`.
    79  	role, err = clt.UpsertRole(ctx, role)
    80  	if err != nil {
    81  		log.Fatalf("failed to create role: %v", err)
    82  	}
    83  
    84  	// Equivalent to `tctl get role/role1`.
    85  	role, err = clt.GetRole(ctx, "role1")
    86  	if err != nil {
    87  		log.Fatalf("failed to get role: %v", err)
    88  	}
    89  
    90  	// Equivalent to `tctl rm role/role1`.
    91  	err = clt.DeleteRole(ctx, "role1")
    92  	if err != nil {
    93  		log.Fatalf("failed to delete role: %v", err)
    94  	}
    95  }
    96  
    97  func ExampleNew() {
    98  	ctx := context.Background()
    99  	clt, err := client.New(ctx, client.Config{
   100  		// Multiple Addresses can be provided to attempt to
   101  		// connect to the auth server. At least one address
   102  		// must be provided, except when using the ProfileCreds.
   103  		Addrs: []string{
   104  			// The Auth server address can be provided to connect locally.
   105  			"auth.example.com:3025",
   106  			// The tunnel proxy address can be provided
   107  			// to connect to the Auth server over SSH.
   108  			"proxy.example.com:3024",
   109  			// The web proxy address can be provided to automatically
   110  			// find the tunnel proxy address and connect using it.
   111  			"proxy.example.com:3080",
   112  		},
   113  		// Multiple Credentials can be provided to attempt to authenticate
   114  		// the client. At least one Credentials object must be provided.
   115  		Credentials: []client.Credentials{
   116  			client.LoadProfile("", ""),
   117  			client.LoadIdentityFile("identity-path"),
   118  			client.LoadKeyPair("cert.crt", "cert.key", "cert.cas"),
   119  			client.LoadIdentityFileFromString(os.Getenv("TELEPORT_IDENTITY")),
   120  		},
   121  		// set to true if your web proxy doesn't have HTTP/TLS certificate
   122  		// configured yet (never use this in production).
   123  		InsecureAddressDiscovery: false,
   124  	})
   125  	if err != nil {
   126  		log.Fatal(err)
   127  	}
   128  	defer clt.Close()
   129  
   130  	clt.Ping(ctx)
   131  }
   132  
   133  // Generate tsh profile with tsh.
   134  //
   135  //	$ tsh login --user=api-user
   136  //
   137  // Load credentials from the default directory and current profile, or specify the directory and profile.
   138  func ExampleCredentials_loadProfile() {
   139  	client.LoadProfile("", "")
   140  	client.LoadProfile("profile-directory", "api-user")
   141  }
   142  
   143  // Load credentials from the default directory and current profile, or specify the directory and profile.
   144  func ExampleLoadProfile() {
   145  	client.LoadProfile("", "")
   146  	client.LoadProfile("profile-directory", "api-user")
   147  }
   148  
   149  // Generate identity file with tsh or tctl.
   150  //
   151  //	$ tsh login --user=api-user --out=identity-file-path
   152  //	$ tctl auth sign --user=api-user --out=identity-file-path
   153  //
   154  // Load credentials from the specified identity file.
   155  func ExampleCredentials_loadIdentity() {
   156  	client.LoadIdentityFile("identity-file-path")
   157  }
   158  
   159  // Load credentials from the specified identity file.
   160  func ExampleLoadIdentityFile() {
   161  	client.LoadIdentityFile("identity-file-path")
   162  }
   163  
   164  // Generate identity file with tsh or tctl.
   165  //
   166  //	$ tsh login --user=api-user --out=identity-file-path
   167  //	$ tctl auth sign --user=api-user --out=identity-file-path
   168  //	$ export TELEPORT_IDENTITY=$(cat identity-file-path)
   169  //
   170  // Load credentials from the envrironment variable.
   171  func ExampleCredentials_loadIdentityString() {
   172  	client.LoadIdentityFileFromString(os.Getenv("TELEPORT_IDENTITY"))
   173  }
   174  
   175  // Load credentials from the specified environment variable.
   176  func ExampleLoadIdentityFileFromString() {
   177  	client.LoadIdentityFileFromString(os.Getenv("TELEPORT_IDENTITY"))
   178  }
   179  
   180  // Generate certificate key pair with tctl.
   181  //
   182  //	$ tctl auth sign --format=tls --user=api-user --out=path/to/certs
   183  //
   184  // Load credentials from the specified certificate files.
   185  func ExampleCredentials_loadKeyPair() {
   186  	client.LoadKeyPair(
   187  		"path/to/certs.crt",
   188  		"path/to/certs.key",
   189  		"path/to/certs.cas",
   190  	)
   191  }
   192  
   193  // Load credentials from the specified certificate files.
   194  func ExampleLoadKeyPair() {
   195  	client.LoadKeyPair(
   196  		"path/to/certs.crt",
   197  		"path/to/certs.key",
   198  		"path/to/certs.cas",
   199  	)
   200  }
   201  
   202  // Perform ALPN handshake test to see if ALPN connection upgrade is required.
   203  //
   204  //	$ TELEPORT_ALPN_TEST_ADDR=proxy.example.com:443 go test -run=ExampleIsALPNConnUpgradeRequired -v
   205  //
   206  // Note that "Output" is set to "false" to mark this as a testable example.
   207  func ExampleIsALPNConnUpgradeRequired() {
   208  	addr := os.Getenv("TELEPORT_ALPN_TEST_ADDR")
   209  	fmt.Println(client.IsALPNConnUpgradeRequired(context.Background(), addr, false))
   210  	// Output: false
   211  }