mirror of
https://github.com/hanzoai/tasks.git
synced 2026-10-04 02:04:03 +00:00
## What changed? Adds JWT to server-to-server connections. Frontend already had support for reading auth so this focuses on getting a token and injecting it. ## Why? s2s is currently a gap in the auth abilities. This provides more flexibility for users based on their auth requirements. ## How did you test it? - [x] built - [x] run locally and tested manually - [x] covered by existing tests - [x] added new unit test(s) - [x] added new functional test(s) ## Potential risks Need to get auth right. Main risk is a user believing they are secure when they are not.
47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
|
|
"google.golang.org/grpc/credentials"
|
|
)
|
|
|
|
// TokenCredentials is a gRPC PerRPCCredentials that attaches a bearer token
|
|
// produced by fetchToken to each outbound RPC. It does no caching; the provider
|
|
// behind fetchToken owns the lifecycle (rotation, expiry-aware refresh,
|
|
// stampede protection). RequireTransportSecurity returns true per RFC 9700.
|
|
type TokenCredentials struct {
|
|
headerName string
|
|
fetchToken func(context.Context) (string, error)
|
|
}
|
|
|
|
var _ credentials.PerRPCCredentials = (*TokenCredentials)(nil)
|
|
|
|
func NewTokenCredentials(
|
|
headerName string,
|
|
fetchToken func(context.Context) (string, error),
|
|
) *TokenCredentials {
|
|
return &TokenCredentials{
|
|
headerName: headerName,
|
|
fetchToken: fetchToken,
|
|
}
|
|
}
|
|
|
|
func (c *TokenCredentials) GetRequestMetadata(ctx context.Context, _ ...string) (map[string]string, error) {
|
|
token, err := c.fetchToken(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if token == "" {
|
|
return nil, nil
|
|
}
|
|
return map[string]string{
|
|
c.headerName: "Bearer " + token,
|
|
}, nil
|
|
}
|
|
|
|
// RequireTransportSecurity returns true so the bearer never attaches to plaintext dials, per RFC 9700.
|
|
func (c *TokenCredentials) RequireTransportSecurity() bool {
|
|
return true
|
|
}
|