-
Notifications
You must be signed in to change notification settings - Fork 0
/
s2s.go
51 lines (41 loc) · 1.19 KB
/
s2s.go
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
package authcontrol
import (
"maps"
"net/http"
"time"
"github.com/go-chi/traceid"
"github.com/go-chi/transport"
)
type S2SClientConfig struct {
Service string
JWTSecret string
DebugRequests bool
}
// Service-to-service HTTP client for internal communication between Sequence services.
func S2SClient(cfg *S2SClientConfig) *http.Client {
httpClient := &http.Client{
Transport: transport.Chain(http.DefaultTransport,
traceid.Transport,
transport.SetHeaderFunc("Authorization", func(req *http.Request) string {
return "BEARER " + S2SToken(cfg.JWTSecret, map[string]any{"service": cfg.Service})
}),
transport.If(cfg.DebugRequests, transport.LogRequests(transport.LogOptions{Concise: true, CURL: true})),
),
}
return httpClient
}
// Create short-lived service-to-service JWT token for internal communication between Sequence services.
func S2SToken(jwtSecret string, claims map[string]any) string {
jwtAuth, _ := NewAuth(jwtSecret).GetVerifier(nil)
now := time.Now().UTC()
c := maps.Clone(claims)
if c == nil {
c = map[string]any{}
}
c["iat"] = now
if _, ok := c["exp"]; !ok {
c["exp"] = now.Add(30 * time.Second)
}
_, t, _ := jwtAuth.Encode(c)
return t
}