summaryrefslogtreecommitdiff
path: root/go/internal/keyline/key_line.go
blob: 7b19c872c8a0b6fe8116fc1fa4d079676fa8774d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package keyline

import (
	"errors"
	"fmt"
	"path"
	"regexp"
	"strings"

	"gitlab.com/gitlab-org/gitlab-shell/go/internal/executable"
)

var (
	keyRegex = regexp.MustCompile(`\A[a-z0-9-]+\z`)
)

const (
	PublicKeyPrefix = "key"
	SshOptions      = "no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty"
)

type KeyLine struct {
	Id      string // This can be either an ID of a Key or username
	Value   string // This can be either a public key or a principal name
	Prefix  string
	RootDir string
}

func NewPublicKeyLine(id string, publicKey string, rootDir string) (*KeyLine, error) {
	if err := validate(id, publicKey); err != nil {
		return nil, err
	}

	return &KeyLine{Id: id, Value: publicKey, Prefix: PublicKeyPrefix, RootDir: rootDir}, nil
}

func (k *KeyLine) ToString() string {
	command := fmt.Sprintf("%s %s-%s", path.Join(k.RootDir, executable.BinDir, executable.GitlabShell), k.Prefix, k.Id)

	return fmt.Sprintf(`command="%s",%s %s`, command, SshOptions, k.Value)
}

func validate(id string, value string) error {
	if !keyRegex.MatchString(id) {
		return errors.New(fmt.Sprintf("Invalid key_id: %s", id))
	}

	if strings.Contains(value, "\n") {
		return errors.New(fmt.Sprintf("Invalid value: %s", value))
	}

	return nil
}