aboutsummaryrefslogtreecommitdiff
path: root/internal/utils/ssh_helpers.go
blob: 903fc112a3a6524df0a62d834a9304fb023507c6 (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 utils

import (
	"fmt"
	"io"
	"net/http"
	"strings"

	"gitlab.com/whiteboardguy/eno/internal/config"
)

func pubkeyServiceURL(username, service string) (string, error) {
	if url, ok := config.Conf.PubkeyServices[service]; ok {
		return strings.ReplaceAll(url, "%s", username), nil
	}

	services := map[string][2]string{
		"github":   {"https://github.com/", ".keys"},
		"gitlab":   {"https://gitlab.com/", ".keys"},
		"codeberg": {"https://codeberg.org", ".keys"},
	}

	s, ok := services[service]
	if !ok {
		return "", fmt.Errorf("unknown service: %s", service)
	}

	return strings.TrimSuffix(s[0], "/") + "/" + username + s[1], nil
}

func GetPubKeyFromService(username, service string) ([]byte, error) {
	url, err := pubkeyServiceURL(username, service)
	if err != nil {
		return nil, err
	}

	resp, err := http.Get(url)
	if err != nil {
		return nil, fmt.Errorf("failed to fetch key from %s: %w", service, err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("%s returned status %d", service, resp.StatusCode)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read response from %s: %w", service, err)
	}

	return body, nil
}