Files
full/all/internal/server/authorization.go

124 lines
3.7 KiB
Go

package server
import (
"context"
"errors"
"fmt"
"net/http"
"path"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
type authorization struct {
key []byte
expire time.Duration
anonymous map[string]struct{}
}
func newAuthorization(key string, expireSeconds int64, anonymous []string) (*authorization, error) {
key = strings.TrimSpace(key)
if key == "" {
return nil, errors.New("authorization key must not be empty")
}
if expireSeconds <= 0 {
return nil, errors.New("authorization expiration must be greater than zero")
}
allowed := make(map[string]struct{}, len(anonymous))
for _, item := range anonymous {
if item = normalizePath(item); item != "" {
allowed[item] = struct{}{}
}
}
return &authorization{key: []byte(key), expire: time.Duration(expireSeconds) * time.Second, anonymous: allowed}, nil
}
func (a *authorization) unaryInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
if !a.isAnonymous(info.FullMethod) {
values := metadata.ValueFromIncomingContext(ctx, "authorization")
if len(values) == 0 {
return nil, status.Error(codes.Unauthenticated, "authorization is required")
}
if err := a.validate(values[0]); err != nil {
return nil, status.Error(codes.Unauthenticated, err.Error())
}
}
return handler(ctx, req)
}
func (a *authorization) httpMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestPath := canonicalHTTPPath(r.URL.Path)
if !a.isAnonymous(requestPath) {
if err := a.validate(r.Header.Get("Authorization")); err != nil {
writeHTTPAuthorizationError(w, err)
return
}
}
next.ServeHTTP(w, r)
})
}
func (a *authorization) validate(raw string) error {
raw = strings.TrimSpace(raw)
if raw == "" {
return errors.New("authorization is required")
}
claims := &jwt.RegisteredClaims{}
tokenValue, err := jwt.ParseWithClaims(raw, claims, func(tokenValue *jwt.Token) (any, error) {
if tokenValue.Method != jwt.SigningMethodHS256 {
return nil, fmt.Errorf("unexpected signing method: %s", tokenValue.Method.Alg())
}
return a.key, nil
}, jwt.WithExpirationRequired(), jwt.WithIssuedAt(), jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
if err != nil || !tokenValue.Valid {
return errors.New("authorization is invalid or expired")
}
if claims.IssuedAt == nil {
return errors.New("authorization issued-at is required")
}
now := time.Now()
if claims.IssuedAt.Time.After(now) || now.Sub(claims.IssuedAt.Time) > a.expire {
return errors.New("authorization is expired")
}
return nil
}
func (a *authorization) isAnonymous(requestPath string) bool {
requestPath = normalizePath(requestPath)
if strings.HasPrefix(requestPath, "/grpc.reflection.") || strings.HasPrefix(requestPath, "/grpc.health.") {
return true
}
_, ok := a.anonymous[requestPath]
return ok
}
func canonicalHTTPPath(requestPath string) string {
normalized := normalizePath(requestPath)
parts := strings.Split(strings.TrimPrefix(normalized, "/"), "/")
if len(parts) == 4 && parts[0] == "rpc" {
return "/" + parts[1] + "." + parts[2] + "/" + parts[3]
}
return normalized
}
func normalizePath(value string) string {
value = strings.TrimSpace(value)
if value == "" {
return ""
}
return path.Clean("/" + strings.TrimPrefix(value, "/"))
}
func writeHTTPAuthorizationError(w http.ResponseWriter, err error) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintf(w, `{"code":%d,"message":%q}`, codes.Unauthenticated, err.Error())
}