Welcome to mirror list, hosted at ThFree Co, Russian Federation.

rpccredentials.go « auth - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ca54901da1d2031011ef8e89d47e5548390733a5 (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
54
55
56
package gitalyauth

import (
	"context"
	"encoding/base64"
	"fmt"
	"strconv"
	"time"

	"google.golang.org/grpc/credentials"
)

// RPCCredentials can be used with grpc.WithPerRPCCredentials to create a
// grpc.DialOption that inserts the supplied token for authentication
// with a Gitaly server.
func RPCCredentials(token string) credentials.PerRPCCredentials {
	return &rpcCredentials{token: base64.StdEncoding.EncodeToString([]byte(token))}
}

type rpcCredentials struct {
	token string
}

func (*rpcCredentials) RequireTransportSecurity() bool { return false }

func (rc *rpcCredentials) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
	return map[string]string{"authorization": "Bearer " + rc.token}, nil
}

// RPCCredentialsV2 can be used with grpc.WithPerRPCCredentials to create a
// grpc.DialOption that inserts an HMAC token with the current timestamp
// for authentication with a Gitaly server.
func RPCCredentialsV2(token string) credentials.PerRPCCredentials {
	return &rpcCredentialsV2{token: token}
}

type rpcCredentialsV2 struct {
	token string
}

func (*rpcCredentialsV2) RequireTransportSecurity() bool { return false }

func (rc *rpcCredentialsV2) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
	return map[string]string{"authorization": "Bearer " + rc.hmacToken()}, nil
}

func (rc *rpcCredentialsV2) hmacToken() string {
	return hmacToken("v2", []byte(rc.token), time.Now())
}

func hmacToken(version string, secret []byte, timestamp time.Time) string {
	intTime := timestamp.Unix()
	signedTimestamp := hmacSign(secret, strconv.FormatInt(intTime, 10))

	return fmt.Sprintf("%s.%x.%d", version, signedTimestamp, intTime)
}