memos/api/v2/acl.go

236 lines
7.1 KiB
Go
Raw Normal View History

package v2
import (
"context"
"net/http"
"strings"
2024-01-28 07:13:11 +08:00
"github.com/golang-jwt/jwt/v5"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
2023-09-17 22:55:13 +08:00
"github.com/usememos/memos/api/auth"
"github.com/usememos/memos/internal/util"
2023-09-17 22:55:13 +08:00
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/store"
)
// ContextKey is the key type of context value.
type ContextKey int
const (
2023-09-14 20:16:17 +08:00
// The key name used to store username in the context
// user id is extracted from the jwt token subject field.
2023-09-14 20:16:17 +08:00
usernameContextKey ContextKey = iota
)
// Used to set modified context of ServerStream.
type WrappedStream struct {
ctx context.Context
stream grpc.ServerStream
}
func (w *WrappedStream) RecvMsg(m any) error {
return w.stream.RecvMsg(m)
}
func (w *WrappedStream) SendMsg(m any) error {
return w.stream.SendMsg(m)
}
func (w *WrappedStream) SendHeader(md metadata.MD) error {
return w.stream.SendHeader(md)
}
func (w *WrappedStream) SetHeader(md metadata.MD) error {
return w.stream.SetHeader(md)
}
func (w *WrappedStream) SetTrailer(md metadata.MD) {
w.stream.SetTrailer(md)
}
func (w *WrappedStream) Context() context.Context {
return w.ctx
}
func newWrappedStream(ctx context.Context, stream grpc.ServerStream) grpc.ServerStream {
return &WrappedStream{ctx, stream}
}
// GRPCAuthInterceptor is the auth interceptor for gRPC server.
type GRPCAuthInterceptor struct {
2023-08-13 00:06:03 +08:00
Store *store.Store
secret string
}
// NewGRPCAuthInterceptor returns a new API auth interceptor.
func NewGRPCAuthInterceptor(store *store.Store, secret string) *GRPCAuthInterceptor {
return &GRPCAuthInterceptor{
2023-08-13 00:06:03 +08:00
Store: store,
secret: secret,
}
}
// AuthenticationInterceptor is the unary interceptor for gRPC API.
func (in *GRPCAuthInterceptor) AuthenticationInterceptor(ctx context.Context, request any, serverInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Errorf(codes.Unauthenticated, "failed to parse metadata from incoming context")
}
2023-09-15 08:18:30 +08:00
accessToken, err := getTokenFromMetadata(md)
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, err.Error())
}
2023-09-15 08:18:30 +08:00
username, err := in.authenticate(ctx, accessToken)
if err != nil {
2023-08-13 00:06:03 +08:00
if isUnauthorizeAllowedMethod(serverInfo.FullMethod) {
return handler(ctx, request)
}
return nil, err
}
2023-08-13 00:06:03 +08:00
user, err := in.Store.GetUser(ctx, &store.FindUser{
2023-09-14 20:16:17 +08:00
Username: &username,
2023-08-13 00:06:03 +08:00
})
if err != nil {
return nil, errors.Wrap(err, "failed to get user")
}
if user == nil {
2023-09-14 20:16:17 +08:00
return nil, errors.Errorf("user %q not exists", username)
2023-08-13 00:06:03 +08:00
}
2023-11-30 20:58:36 +08:00
if user.RowStatus == store.Archived {
return nil, errors.Errorf("user %q is archived", username)
}
2023-08-13 00:06:03 +08:00
if isOnlyForAdminAllowedMethod(serverInfo.FullMethod) && user.Role != store.RoleHost && user.Role != store.RoleAdmin {
2023-09-14 20:16:17 +08:00
return nil, errors.Errorf("user %q is not admin", username)
2023-08-13 00:06:03 +08:00
}
// Stores userID into context.
2023-09-14 20:16:17 +08:00
childCtx := context.WithValue(ctx, usernameContextKey, username)
return handler(childCtx, request)
}
func (in *GRPCAuthInterceptor) StreamAuthenticationInterceptor(srv any, stream grpc.ServerStream, serverInfo *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
md, ok := metadata.FromIncomingContext(stream.Context())
if !ok {
return status.Errorf(codes.Unauthenticated, "failed to parse metadata from incoming context")
}
accessToken, err := getTokenFromMetadata(md)
if err != nil {
return status.Errorf(codes.Unauthenticated, err.Error())
}
username, err := in.authenticate(stream.Context(), accessToken)
if err != nil {
if isUnauthorizeAllowedMethod(serverInfo.FullMethod) {
return handler(stream.Context(), stream)
}
return err
}
user, err := in.Store.GetUser(stream.Context(), &store.FindUser{
Username: &username,
})
if err != nil {
return errors.Wrap(err, "failed to get user")
}
if user == nil {
return errors.Errorf("user %q not exists", username)
}
if user.RowStatus == store.Archived {
return errors.Errorf("user %q is archived", username)
}
if isOnlyForAdminAllowedMethod(serverInfo.FullMethod) && user.Role != store.RoleHost && user.Role != store.RoleAdmin {
return errors.Errorf("user %q is not admin", username)
}
// Stores userID into context.
childCtx := context.WithValue(stream.Context(), usernameContextKey, username)
return handler(srv, newWrappedStream(childCtx, stream))
}
2023-09-15 08:18:30 +08:00
func (in *GRPCAuthInterceptor) authenticate(ctx context.Context, accessToken string) (string, error) {
if accessToken == "" {
2023-09-14 20:16:17 +08:00
return "", status.Errorf(codes.Unauthenticated, "access token not found")
}
2023-09-14 20:16:17 +08:00
claims := &auth.ClaimsMessage{}
2023-09-15 08:18:30 +08:00
_, err := jwt.ParseWithClaims(accessToken, claims, func(t *jwt.Token) (any, error) {
if t.Method.Alg() != jwt.SigningMethodHS256.Name {
return nil, status.Errorf(codes.Unauthenticated, "unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)
}
if kid, ok := t.Header["kid"].(string); ok {
if kid == "v1" {
return []byte(in.secret), nil
}
}
return nil, status.Errorf(codes.Unauthenticated, "unexpected access token kid=%v", t.Header["kid"])
})
if err != nil {
2023-09-14 20:16:17 +08:00
return "", status.Errorf(codes.Unauthenticated, "Invalid or expired access token")
}
2023-09-18 21:50:59 +08:00
// We either have a valid access token or we will attempt to generate new access token.
userID, err := util.ConvertStringToInt32(claims.Subject)
if err != nil {
return "", errors.Wrap(err, "malformed ID in the token")
}
2023-08-13 00:06:03 +08:00
user, err := in.Store.GetUser(ctx, &store.FindUser{
2023-09-18 21:50:59 +08:00
ID: &userID,
})
if err != nil {
2023-09-14 20:16:17 +08:00
return "", errors.Wrap(err, "failed to get user")
}
if user == nil {
2023-09-18 21:50:59 +08:00
return "", errors.Errorf("user %q not exists", userID)
}
if user.RowStatus == store.Archived {
2023-09-18 21:50:59 +08:00
return "", errors.Errorf("user %q is archived", userID)
}
2023-09-15 08:18:30 +08:00
accessTokens, err := in.Store.GetUserAccessTokens(ctx, user.ID)
if err != nil {
return "", errors.Wrapf(err, "failed to get user access tokens")
}
if !validateAccessToken(accessToken, accessTokens) {
return "", status.Errorf(codes.Unauthenticated, "invalid access token")
}
2023-09-18 21:50:59 +08:00
return user.Username, nil
}
func getTokenFromMetadata(md metadata.MD) (string, error) {
2023-09-25 20:14:01 +08:00
// Check the HTTP request header first.
authorizationHeaders := md.Get("Authorization")
if len(md.Get("Authorization")) > 0 {
authHeaderParts := strings.Fields(authorizationHeaders[0])
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
2023-09-29 13:04:54 +08:00
return "", errors.New("authorization header format must be Bearer {token}")
}
return authHeaderParts[1], nil
}
2023-09-25 20:14:01 +08:00
// Check the cookie header.
var accessToken string
for _, t := range append(md.Get("grpcgateway-cookie"), md.Get("cookie")...) {
header := http.Header{}
header.Add("Cookie", t)
request := http.Request{Header: header}
if v, _ := request.Cookie(auth.AccessTokenCookieName); v != nil {
accessToken = v.Value
}
}
return accessToken, nil
}
2023-09-15 08:18:30 +08:00
func validateAccessToken(accessTokenString string, userAccessTokens []*storepb.AccessTokensUserSetting_AccessToken) bool {
for _, userAccessToken := range userAccessTokens {
if accessTokenString == userAccessToken.AccessToken {
return true
}
}
return false
}