1package api
2
3import (
4	"context"
5	"fmt"
6)
7
8// SSH is used to return a client to invoke operations on SSH backend.
9type SSH struct {
10	c          *Client
11	MountPoint string
12}
13
14// SSH returns the client for logical-backend API calls.
15func (c *Client) SSH() *SSH {
16	return c.SSHWithMountPoint(SSHHelperDefaultMountPoint)
17}
18
19// SSHWithMountPoint returns the client with specific SSH mount point.
20func (c *Client) SSHWithMountPoint(mountPoint string) *SSH {
21	return &SSH{
22		c:          c,
23		MountPoint: mountPoint,
24	}
25}
26
27// Credential invokes the SSH backend API to create a credential to establish an SSH session.
28func (c *SSH) Credential(role string, data map[string]interface{}) (*Secret, error) {
29	r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/%s/creds/%s", c.MountPoint, role))
30	if err := r.SetJSONBody(data); err != nil {
31		return nil, err
32	}
33
34	ctx, cancelFunc := context.WithCancel(context.Background())
35	defer cancelFunc()
36	resp, err := c.c.RawRequestWithContext(ctx, r)
37	if err != nil {
38		return nil, err
39	}
40	defer resp.Body.Close()
41
42	return ParseSecret(resp.Body)
43}
44
45// SignKey signs the given public key and returns a signed public key to pass
46// along with the SSH request.
47func (c *SSH) SignKey(role string, data map[string]interface{}) (*Secret, error) {
48	r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/%s/sign/%s", c.MountPoint, role))
49	if err := r.SetJSONBody(data); err != nil {
50		return nil, err
51	}
52
53	ctx, cancelFunc := context.WithCancel(context.Background())
54	defer cancelFunc()
55	resp, err := c.c.RawRequestWithContext(ctx, r)
56	if err != nil {
57		return nil, err
58	}
59	defer resp.Body.Close()
60
61	return ParseSecret(resp.Body)
62}
63