Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: set access token, refresh token, user ID to cookie on login (#4077)
Danny Xuaf4a3bb36510
diff --git a/frontend/src/types/proto/v1/auth_service.ts b/frontend/src/types/proto/v1/auth_service.tsindex 918d163f50..f06c0972b3 100644--- a/frontend/src/types/proto/v1/auth_service.ts+++ b/frontend/src/types/proto/v1/auth_service.ts@@ -1,19 +1,25 @@/* eslint-disable */import _m0 from "protobufjs/minimal";+import { Empty } from "../google/protobuf/empty";export const protobufPackage = "bytebase.v1";export interface LoginRequest {email: string;password: string;+ /** If web is set, we will set access token, refresh token, and user to the cookie. */+ web: boolean;}export interface LoginResponse {token: string;}+export interface LogoutRequest {+}+function createBaseLoginRequest(): LoginRequest {- return { email: "", password: "" };+ return { email: "", password: "", web: false };}export const LoginRequest = {@@ -24,6 +30,9 @@ export const LoginRequest = {if (message.password !== "") {writer.uint32(18).string(message.password);}+ if (message.web === true) {+ writer.uint32(24).bool(message.web);+ }return writer;},@@ -40,6 +49,9 @@ export const LoginRequest = {case 2:message.password = reader.string();break;+ case 3:+ message.web = reader.bool();+ break;default:reader.skipType(tag & 7);break;@@ -52,6 +64,7 @@ export const LoginRequest = {return {email: isSet(object.email) ? String(object.email) : "",password: isSet(object.password) ? String(object.password) : "",+ web: isSet(object.web) ? Boolean(object.web) : false,};},@@ -59,6 +72,7 @@ export const LoginRequest = {const obj: any = {};message.email !== undefined && (obj.email = message.email);message.password !== undefined && (obj.password = message.password);+ message.web !== undefined && (obj.web = message.web);return obj;},@@ -66,6 +80,7 @@ export const LoginRequest = {const message = createBaseLoginRequest();message.email = object.email ?? "";message.password = object.password ?? "";+ message.web = object.web ?? false;return message;},};@@ -117,8 +132,48 @@ export const LoginResponse = {},};+function createBaseLogoutRequest(): LogoutRequest {+ return {};+}++export const LogoutRequest = {+ encode(_: LogoutRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {+ return writer;+ },++ decode(input: _m0.Reader | Uint8Array, length?: number): LogoutRequest {+ const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);+ let end = length === undefined ? reader.len : reader.pos + length;+ const message = createBaseLogoutRequest();+ while (reader.pos < end) {+ const tag = reader.uint32();+ switch (tag >>> 3) {+ default:+ reader.skipType(tag & 7);+ break;+ }+ }+ return message;+ },++ fromJSON(_: any): LogoutRequest {+ return {};+ },++ toJSON(_: LogoutRequest): unknown {+ const obj: any = {};+ return obj;+ },++ fromPartial<I extends Exact<DeepPartial<LogoutRequest>, I>>(_: I): LogoutRequest {+ const message = createBaseLogoutRequest();+ return message;+ },+};+export interface AuthService {Login(request: LoginRequest): Promise<LoginResponse>;+ Logout(request: LogoutRequest): Promise<Empty>;}export class AuthServiceClientImpl implements AuthService {@@ -128,12 +183,19 @@ export class AuthServiceClientImpl implements AuthService {this.service = opts?.service || "bytebase.v1.AuthService";this.rpc = rpc;this.Login = this.Login.bind(this);+ this.Logout = this.Logout.bind(this);}Login(request: LoginRequest): Promise<LoginResponse> {const data = LoginRequest.encode(request).finish();const promise = this.rpc.request(this.service, "Login", data);return promise.then((data) => LoginResponse.decode(new _m0.Reader(data)));}++ Logout(request: LogoutRequest): Promise<Empty> {+ const data = LogoutRequest.encode(request).finish();+ const promise = this.rpc.request(this.service, "Logout", data);+ return promise.then((data) => Empty.decode(new _m0.Reader(data)));+ }}interface Rpc {diff --git a/proto/generated-go/v1/auth_service.pb.go b/proto/generated-go/v1/auth_service.pb.goindex 38daa35e76..991b737b85 100644--- a/proto/generated-go/v1/auth_service.pb.go+++ b/proto/generated-go/v1/auth_service.pb.go@@ -10,6 +10,7 @@ import (_ "google.golang.org/genproto/googleapis/api/annotations"protoreflect "google.golang.org/protobuf/reflect/protoreflect"protoimpl "google.golang.org/protobuf/runtime/protoimpl"+ emptypb "google.golang.org/protobuf/types/known/emptypb"reflect "reflect"sync "sync")@@ -28,6 +29,8 @@ type LoginRequest struct {Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"`+ // If web is set, we will set access token, refresh token, and user to the cookie.+ Web bool `protobuf:"varint,3,opt,name=web,proto3" json:"web,omitempty"`}func (x *LoginRequest) Reset() {@@ -76,6 +79,13 @@ func (x *LoginRequest) GetPassword() string {return ""}+func (x *LoginRequest) GetWeb() bool {+ if x != nil {+ return x.Web+ }+ return false+}+type LoginResponse struct {state protoimpl.MessageStatesizeCache protoimpl.SizeCache@@ -123,6 +133,44 @@ func (x *LoginResponse) GetToken() string {return ""}+type LogoutRequest struct {+ state protoimpl.MessageState+ sizeCache protoimpl.SizeCache+ unknownFields protoimpl.UnknownFields+}++func (x *LogoutRequest) Reset() {+ *x = LogoutRequest{}+ if protoimpl.UnsafeEnabled {+ mi := &file_v1_auth_service_proto_msgTypes[2]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+ }+}++func (x *LogoutRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*LogoutRequest) ProtoMessage() {}++func (x *LogoutRequest) ProtoReflect() protoreflect.Message {+ mi := &file_v1_auth_service_proto_msgTypes[2]+ if protoimpl.UnsafeEnabled && x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use LogoutRequest.ProtoReflect.Descriptor instead.+func (*LogoutRequest) Descriptor() ([]byte, []int) {+ return file_v1_auth_service_proto_rawDescGZIP(), []int{2}+}+var File_v1_auth_service_proto protoreflect.FileDescriptorvar file_v1_auth_service_proto_rawDesc = []byte{@@ -130,21 +178,31 @@ var file_v1_auth_service_proto_rawDesc = []byte{0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0b, 0x62, 0x79, 0x74, 0x65, 0x62, 0x61, 0x73,0x65, 0x2e, 0x76, 0x31, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69,0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f,- 0x74, 0x6f, 0x22, 0x40, 0x0a, 0x0c, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65,- 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28,- 0x09, 0x52, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73,- 0x77, 0x6f, 0x72, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73,- 0x77, 0x6f, 0x72, 0x64, 0x22, 0x25, 0x0a, 0x0d, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x73,- 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01,- 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x32, 0x68, 0x0a, 0x0b, 0x41,- 0x75, 0x74, 0x68, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x59, 0x0a, 0x05, 0x4c, 0x6f,- 0x67, 0x69, 0x6e, 0x12, 0x19, 0x2e, 0x62, 0x79, 0x74, 0x65, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x76,- 0x31, 0x2e, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1a,- 0x2e, 0x62, 0x79, 0x74, 0x65, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x6f, 0x67,- 0x69, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x19, 0x82, 0xd3, 0xe4, 0x93,- 0x02, 0x13, 0x3a, 0x01, 0x2a, 0x22, 0x0e, 0x2f, 0x76, 0x31, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f,- 0x6c, 0x6f, 0x67, 0x69, 0x6e, 0x42, 0x11, 0x5a, 0x0f, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74,- 0x65, 0x64, 0x2d, 0x67, 0x6f, 0x2f, 0x76, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,+ 0x74, 0x6f, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f,+ 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22,+ 0x52, 0x0a, 0x0c, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12,+ 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05,+ 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72,+ 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72,+ 0x64, 0x12, 0x10, 0x0a, 0x03, 0x77, 0x65, 0x62, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x03,+ 0x77, 0x65, 0x62, 0x22, 0x25, 0x0a, 0x0d, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x73, 0x70,+ 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20,+ 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x0f, 0x0a, 0x0d, 0x4c, 0x6f,+ 0x67, 0x6f, 0x75, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x32, 0xc2, 0x01, 0x0a, 0x0b,+ 0x41, 0x75, 0x74, 0x68, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x59, 0x0a, 0x05, 0x4c,+ 0x6f, 0x67, 0x69, 0x6e, 0x12, 0x19, 0x2e, 0x62, 0x79, 0x74, 0x65, 0x62, 0x61, 0x73, 0x65, 0x2e,+ 0x76, 0x31, 0x2e, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a,+ 0x1a, 0x2e, 0x62, 0x79, 0x74, 0x65, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x6f,+ 0x67, 0x69, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x19, 0x82, 0xd3, 0xe4,+ 0x93, 0x02, 0x13, 0x3a, 0x01, 0x2a, 0x22, 0x0e, 0x2f, 0x76, 0x31, 0x2f, 0x61, 0x75, 0x74, 0x68,+ 0x2f, 0x6c, 0x6f, 0x67, 0x69, 0x6e, 0x12, 0x58, 0x0a, 0x06, 0x4c, 0x6f, 0x67, 0x6f, 0x75, 0x74,+ 0x12, 0x1a, 0x2e, 0x62, 0x79, 0x74, 0x65, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x4c,+ 0x6f, 0x67, 0x6f, 0x75, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67,+ 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45,+ 0x6d, 0x70, 0x74, 0x79, 0x22, 0x1a, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x14, 0x3a, 0x01, 0x2a, 0x22,+ 0x0f, 0x2f, 0x76, 0x31, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x6c, 0x6f, 0x67, 0x6f, 0x75, 0x74,+ 0x42, 0x11, 0x5a, 0x0f, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x64, 0x2d, 0x67, 0x6f,+ 0x2f, 0x76, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,}var (@@ -159,16 +217,20 @@ func file_v1_auth_service_proto_rawDescGZIP() []byte {return file_v1_auth_service_proto_rawDescData}-var file_v1_auth_service_proto_msgTypes = make([]protoimpl.MessageInfo, 2)+var file_v1_auth_service_proto_msgTypes = make([]protoimpl.MessageInfo, 3)var file_v1_auth_service_proto_goTypes = []interface{}{(*LoginRequest)(nil), // 0: bytebase.v1.LoginRequest(*LoginResponse)(nil), // 1: bytebase.v1.LoginResponse+ (*LogoutRequest)(nil), // 2: bytebase.v1.LogoutRequest+ (*emptypb.Empty)(nil), // 3: google.protobuf.Empty}var file_v1_auth_service_proto_depIdxs = []int32{0, // 0: bytebase.v1.AuthService.Login:input_type -> bytebase.v1.LoginRequest- 1, // 1: bytebase.v1.AuthService.Login:output_type -> bytebase.v1.LoginResponse- 1, // [1:2] is the sub-list for method output_type- 0, // [0:1] is the sub-list for method input_type+ 2, // 1: bytebase.v1.AuthService.Logout:input_type -> bytebase.v1.LogoutRequest+ 1, // 2: bytebase.v1.AuthService.Login:output_type -> bytebase.v1.LoginResponse+ 3, // 3: bytebase.v1.AuthService.Logout:output_type -> google.protobuf.Empty+ 2, // [2:4] is the sub-list for method output_type+ 0, // [0:2] is the sub-list for method input_type0, // [0:0] is the sub-list for extension type_name0, // [0:0] is the sub-list for extension extendee0, // [0:0] is the sub-list for field type_name@@ -204,6 +266,18 @@ func file_v1_auth_service_proto_init() {return nil}}+ file_v1_auth_service_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {+ switch v := v.(*LogoutRequest); i {+ case 0:+ return &v.state+ case 1:+ return &v.sizeCache+ case 2:+ return &v.unknownFields+ default:+ return nil+ }+ }}type x struct{}out := protoimpl.TypeBuilder{@@ -211,7 +285,7 @@ func file_v1_auth_service_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: file_v1_auth_service_proto_rawDesc,NumEnums: 0,- NumMessages: 2,+ NumMessages: 3,NumExtensions: 0,NumServices: 1,},diff --git a/proto/generated-go/v1/auth_service.pb.gw.go b/proto/generated-go/v1/auth_service.pb.gw.goindex 00a1c8e621..3267ff4c97 100644--- a/proto/generated-go/v1/auth_service.pb.gw.go+++ b/proto/generated-go/v1/auth_service.pb.gw.go@@ -65,6 +65,40 @@ func local_request_AuthService_Login_0(ctx context.Context, marshaler runtime.Ma}+func request_AuthService_Logout_0(ctx context.Context, marshaler runtime.Marshaler, client AuthServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+ var protoReq LogoutRequest+ var metadata runtime.ServerMetadata++ newReader, berr := utilities.IOReaderFactory(req.Body)+ if berr != nil {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)+ }+ if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)+ }++ msg, err := client.Logout(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))+ return msg, metadata, err++}++func local_request_AuthService_Logout_0(ctx context.Context, marshaler runtime.Marshaler, server AuthServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+ var protoReq LogoutRequest+ var metadata runtime.ServerMetadata++ newReader, berr := utilities.IOReaderFactory(req.Body)+ if berr != nil {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)+ }+ if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)+ }++ msg, err := server.Logout(ctx, &protoReq)+ return msg, metadata, err++}+// RegisterAuthServiceHandlerServer registers the http handlers for service AuthService to "mux".// UnaryRPC :call AuthServiceServer directly.// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.@@ -96,6 +130,31 @@ func RegisterAuthServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux})+ mux.Handle("POST", pattern_AuthService_Logout_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ var stream runtime.ServerTransportStream+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)+ var err error+ var annotatedContext context.Context+ annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.AuthService/Logout", runtime.WithHTTPPathPattern("/v1/auth/logout"))+ if err != nil {+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)+ return+ }+ resp, md, err := local_request_AuthService_Logout_0(annotatedContext, inboundMarshaler, server, req, pathParams)+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)+ if err != nil {+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)+ return+ }++ forward_AuthService_Logout_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)++ })+return nil}@@ -159,13 +218,39 @@ func RegisterAuthServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux})+ mux.Handle("POST", pattern_AuthService_Logout_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)+ var err error+ var annotatedContext context.Context+ annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.AuthService/Logout", runtime.WithHTTPPathPattern("/v1/auth/logout"))+ if err != nil {+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)+ return+ }+ resp, md, err := request_AuthService_Logout_0(annotatedContext, inboundMarshaler, client, req, pathParams)+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)+ if err != nil {+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)+ return+ }++ forward_AuthService_Logout_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)++ })+return nil}var (pattern_AuthService_Login_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "auth", "login"}, ""))++ pattern_AuthService_Logout_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "auth", "logout"}, "")))var (forward_AuthService_Login_0 = runtime.ForwardResponseMessage++ forward_AuthService_Logout_0 = runtime.ForwardResponseMessage)diff --git a/proto/generated-go/v1/auth_service_grpc.pb.go b/proto/generated-go/v1/auth_service_grpc.pb.goindex 8c3d8c68ea..ccea269f77 100644--- a/proto/generated-go/v1/auth_service_grpc.pb.go+++ b/proto/generated-go/v1/auth_service_grpc.pb.go@@ -11,6 +11,7 @@ import (grpc "google.golang.org/grpc"codes "google.golang.org/grpc/codes"status "google.golang.org/grpc/status"+ emptypb "google.golang.org/protobuf/types/known/emptypb")// This is a compile-time assertion to ensure that this generated file@@ -23,6 +24,7 @@ const _ = grpc.SupportPackageIsVersion7// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.type AuthServiceClient interface {Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error)+ Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)}type authServiceClient struct {@@ -42,11 +44,21 @@ func (c *authServiceClient) Login(ctx context.Context, in *LoginRequest, opts ..return out, nil}+func (c *authServiceClient) Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) {+ out := new(emptypb.Empty)+ err := c.cc.Invoke(ctx, "/bytebase.v1.AuthService/Logout", in, out, opts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+// AuthServiceServer is the server API for AuthService service.// All implementations must embed UnimplementedAuthServiceServer// for forward compatibilitytype AuthServiceServer interface {Login(context.Context, *LoginRequest) (*LoginResponse, error)+ Logout(context.Context, *LogoutRequest) (*emptypb.Empty, error)mustEmbedUnimplementedAuthServiceServer()}@@ -57,6 +69,9 @@ type UnimplementedAuthServiceServer struct {func (UnimplementedAuthServiceServer) Login(context.Context, *LoginRequest) (*LoginResponse, error) {return nil, status.Errorf(codes.Unimplemented, "method Login not implemented")}+func (UnimplementedAuthServiceServer) Logout(context.Context, *LogoutRequest) (*emptypb.Empty, error) {+ return nil, status.Errorf(codes.Unimplemented, "method Logout not implemented")+}func (UnimplementedAuthServiceServer) mustEmbedUnimplementedAuthServiceServer() {}// UnsafeAuthServiceServer may be embedded to opt out of forward compatibility for this service.@@ -88,6 +103,24 @@ func _AuthService_Login_Handler(srv interface{}, ctx context.Context, dec func(ireturn interceptor(ctx, in, info, handler)}+func _AuthService_Logout_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(LogoutRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AuthServiceServer).Logout(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: "/bytebase.v1.AuthService/Logout",+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AuthServiceServer).Logout(ctx, req.(*LogoutRequest))+ }+ return interceptor(ctx, in, info, handler)+}+// AuthService_ServiceDesc is the grpc.ServiceDesc for AuthService service.// It's only intended for direct use with grpc.RegisterService,// and not to be introspected or modified (even as a copy)@@ -99,6 +132,10 @@ var AuthService_ServiceDesc = grpc.ServiceDesc{MethodName: "Login",Handler: _AuthService_Login_Handler,},+ {+ MethodName: "Logout",+ Handler: _AuthService_Logout_Handler,+ },},Streams: []grpc.StreamDesc{},Metadata: "v1/auth_service.proto",diff --git a/proto/v1/auth_service.proto b/proto/v1/auth_service.protoindex d3a53d7f04..21652cebf9 100644--- a/proto/v1/auth_service.proto+++ b/proto/v1/auth_service.proto@@ -3,6 +3,7 @@ syntax = "proto3";package bytebase.v1;import "google/api/annotations.proto";+import "google/protobuf/empty.proto";option go_package = "generated-go/v1";@@ -13,14 +14,26 @@ service AuthService {body: "*"};}+ rpc Logout(LogoutRequest) returns (google.protobuf.Empty) {+ option (google.api.http) = {+ post: "/v1/auth/logout"+ body: "*"+ };+ }}message LoginRequest {string email = 1;string password = 2;++ // If web is set, we will set access token, refresh token, and user to the cookie.+ bool web = 3;}message LoginResponse {string token = 1;-}\ No newline at end of file+}++message LogoutRequest {+}diff --git a/server/api/auth/auth.go b/server/api/auth/auth.goindex c4208ffcdc..ba6b07c567 100644--- a/server/api/auth/auth.go+++ b/server/api/auth/auth.go@@ -5,6 +5,7 @@ import ("context""errors""fmt"+ "net/http""strconv""strings""time"@@ -15,6 +16,7 @@ import ("google.golang.org/grpc/status""github.com/golang-jwt/jwt/v4"+ errs "github.com/pkg/errors""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"@@ -26,9 +28,36 @@ const (issuer = "bytebase"// Signing key section. For now, this is only used for signing, not for verifying since we only// have 1 version. But it will be used to maintain backward compatibility if we change the signing mechanism.- keyID = "v1"- accessTokenAudienceFmt = "bb.user.access.%s"- apiTokenDuration = 2 * time.Hour+ keyID = "v1"+ // AccessTokenAudienceFmt is the format of the acccess token audience.+ AccessTokenAudienceFmt = "bb.user.access.%s"+ // RefreshTokenAudienceFmt is the format of the refresh token audience.+ RefreshTokenAudienceFmt = "bb.user.refresh.%s"+ apiTokenDuration = 2 * time.Hour+ accessTokenDuration = 24 * time.Hour+ refreshTokenDuration = 7 * 24 * time.Hour+ // RefreshThresholdDuration is the threshold duration for refreshing token.+ RefreshThresholdDuration = 1 * time.Hour++ // CookieExpDuration expires slightly earlier than the jwt expiration. Client would be logged out if the user+ // cookie expires, thus the client would always logout first before attempting to make a request with the expired jwt.+ // Suppose we have a valid refresh token, we will refresh the token in 2 cases:+ // 1. The access token is about to expire in <<refreshThresholdDuration>>+ // 2. The access token has already expired, we refresh the token so that the ongoing request can pass through.+ CookieExpDuration = refreshTokenDuration - 1*time.Minute+ // AccessTokenCookieName is the cookie name of access token.+ AccessTokenCookieName = "access-token"+ // RefreshTokenCookieName is the cookie name of refresh token.+ RefreshTokenCookieName = "refresh-token"+ // UserIDCookieName is the cookie name of user ID.+ UserIDCookieName = "user"++ // GatewayMetadataAccessTokenKey is the gateway metadata key for access token.+ GatewayMetadataAccessTokenKey = "bytebase-access-token"+ // GatewayMetadataRefreshTokenKey is the gateway metadata key for refresh token.+ GatewayMetadataRefreshTokenKey = "bytebase-refresh-token"+ // GatewayMetadataUserIDKey is the gateway metadata key for user ID.+ GatewayMetadataUserIDKey = "bytebase-user")// APIAuthInterceptor is the auth interceptor for gRPC server.@@ -61,18 +90,14 @@ func (in *APIAuthInterceptor) AuthenticationInterceptor(ctx context.Context, reqif !ok {return nil, status.Error(codes.Unauthenticated, "failed to parse metadata from incoming context")}- if len(md.Get("Authorization")) == 0 {- return nil, status.Error(codes.Unauthenticated, "failed to get authorization metadata from incoming context")- }- authorization := md.Get("Authorization")[0]- authHeaderParts := strings.Fields(authorization)- if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {- return nil, status.Error(codes.Unauthenticated, "authorization header format must be Bearer {token}")+ accessTokenStr, refreshTokenStr, err := getTokenFromMetadata(md)+ if err != nil {+ return nil, status.Error(codes.Unauthenticated, err.Error())}- token := authHeaderParts[1]- claims := &claims{}- if _, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (interface{}, error) {+ claims := &claimsMessage{}+ generateToken := false+ accessToken, err := jwt.ParseWithClaims(accessTokenStr, claims, func(t *jwt.Token) (interface{}, 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)}@@ -82,24 +107,30 @@ func (in *APIAuthInterceptor) AuthenticationInterceptor(ctx context.Context, req}}return nil, status.Errorf(codes.Unauthenticated, "unexpected access token kid=%v", t.Header["kid"])- }); err != nil {+ })+ if err != nil {var ve *jwt.ValidationError- if errors.As(err, &ve) {+ if errors.As(err, &ve) && ve.Errors == jwt.ValidationErrorExpired {// If expiration error is the only error, we will clear the err// and generate new access token and refresh token- if ve.Errors == jwt.ValidationErrorExpired {+ if refreshTokenStr == "" {return nil, status.Errorf(codes.Unauthenticated, "access token is expired")}+ generateToken = true+ } else {+ return nil, status.Errorf(codes.Unauthenticated, "failed to parse claim")}- return nil, status.Errorf(codes.Unauthenticated, "failed to parse claim")}- if !audienceContains(claims.Audience, fmt.Sprintf(accessTokenAudienceFmt, in.mode)) {+ if !audienceContains(claims.Audience, fmt.Sprintf(AccessTokenAudienceFmt, in.mode)) {return nil, status.Errorf(codes.Unauthenticated,"invalid access token, audience mismatch, got %q, expected %q. you may send request to the wrong environment",claims.Audience,- fmt.Sprintf(accessTokenAudienceFmt, in.mode),+ fmt.Sprintf(AccessTokenAudienceFmt, in.mode),)}+ if time.Until(claims.ExpiresAt.Time) < RefreshThresholdDuration {+ generateToken = true+ }principalID, err := strconv.Atoi(claims.Subject)if err != nil {@@ -112,11 +143,87 @@ func (in *APIAuthInterceptor) AuthenticationInterceptor(ctx context.Context, reqif user == nil {return nil, status.Errorf(codes.Unauthenticated, "user ID %q not exists in the access token", principalID)}++ if generateToken {+ generateTokenFunc := func() error {+ // Parses token and checks if it's valid.+ refreshTokenClaims := &claimsMessage{}+ refreshToken, err := jwt.ParseWithClaims(refreshTokenStr, refreshTokenClaims, func(t *jwt.Token) (interface{}, error) {+ if t.Method.Alg() != jwt.SigningMethodHS256.Name {+ return nil, status.Errorf(codes.Unauthenticated, "unexpected refresh token signing method=%v, expected %v", t.Header["alg"], jwt.SigningMethodHS256)+ }++ if kid, ok := t.Header["kid"].(string); ok {+ if kid == "v1" {+ return []byte(in.secret), nil+ }+ }+ return nil, errs.Errorf("unexpected refresh token kid=%v", t.Header["kid"])+ })+ if err != nil {+ if err == jwt.ErrSignatureInvalid {+ return errs.Errorf("failed to generate access token: invalid refresh token signature")+ }+ return errs.Errorf("Server error to refresh expired token, user ID %d", principalID)+ }++ if !audienceContains(refreshTokenClaims.Audience, fmt.Sprintf(RefreshTokenAudienceFmt, in.mode)) {+ return errs.Errorf("Invalid refresh token, audience mismatch, got %q, expected %q. you may send request to the wrong environment",+ refreshTokenClaims.Audience,+ fmt.Sprintf(RefreshTokenAudienceFmt, in.mode),+ )+ }++ // If we have a valid refresh token, we will generate new access token and refresh token+ if refreshToken != nil && refreshToken.Valid {+ if err := generateTokensAndSetCookies(ctx, user, in.mode, in.secret); err != nil {+ return errs.Wrapf(err, "failed to regenerate token")+ }+ }++ return nil+ }++ // It may happen that we still have a valid access token, but we encounter issue when trying to generate new token+ // In such case, we won't return the error.+ if err := generateTokenFunc(); err != nil && !accessToken.Valid {+ return nil, status.Errorf(codes.Unauthenticated, err.Error())+ }+ }+// Stores principalID into context.childCtx := context.WithValue(ctx, common.PrincipalIDContextKey, principalID)return handler(childCtx, req)}+func getTokenFromMetadata(md metadata.MD) (string, string, error) {+ authorizationHeaders := md.Get("Authorization")+ if len(md.Get("Authorization")) > 0 {+ authHeaderParts := strings.Fields(authorizationHeaders[0])+ if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {+ return "", "", errs.Errorf("authorization header format must be Bearer {token}")+ }+ return authHeaderParts[1], "", nil+ }+ // check the HTTP cookie+ var accessToken, refreshToken string+ for _, t := range md["grpcgateway-cookie"] {+ header := http.Header{}+ header.Add("Cookie", t)+ request := http.Request{Header: header}+ if v, _ := request.Cookie(AccessTokenCookieName); v != nil {+ accessToken = v.Value+ }+ if v, _ := request.Cookie(RefreshTokenCookieName); v != nil {+ refreshToken = v.Value+ }+ }+ if accessToken != "" && refreshToken != "" {+ return accessToken, refreshToken, nil+ }+ return "", "", errs.Errorf("access token not found from metadata")+}+func audienceContains(audience jwt.ClaimStrings, token string) bool {for _, v := range audience {if v == token {@@ -126,21 +233,55 @@ func audienceContains(audience jwt.ClaimStrings, token string) bool {return false}-type claims struct {+type claimsMessage struct {Name string `json:"name"`jwt.RegisteredClaims}+// generateTokensAndSetCookies generates jwt token and saves it to the http-only cookie.+func generateTokensAndSetCookies(ctx context.Context, user *api.Principal, mode common.ReleaseMode, secret string) error {+ accessToken, err := GenerateAccessToken(user, mode, secret)+ if err != nil {+ return errs.Wrap(err, "failed to generate access token")+ }+ // We generate here a new refresh token and saving it to the cookie.+ refreshToken, err := GenerateRefreshToken(user, mode, secret)+ if err != nil {+ return errs.Wrap(err, "failed to generate refresh token")+ }++ if err := grpc.SetHeader(ctx, metadata.New(map[string]string{+ GatewayMetadataAccessTokenKey: accessToken,+ GatewayMetadataRefreshTokenKey: refreshToken,+ GatewayMetadataUserIDKey: fmt.Sprintf("%d", user.ID),+ })); err != nil {+ return errs.Wrapf(err, "failed to set grpc header")+ }+ return nil+}+// GenerateAPIToken generates an API token.func GenerateAPIToken(user *api.Principal, mode common.ReleaseMode, secret string) (string, error) {expirationTime := time.Now().Add(apiTokenDuration)- return generateToken(user, fmt.Sprintf(accessTokenAudienceFmt, mode), expirationTime, []byte(secret))+ return generateToken(user, fmt.Sprintf(AccessTokenAudienceFmt, mode), expirationTime, []byte(secret))+}++// GenerateAccessToken generates an access token for web.+func GenerateAccessToken(user *api.Principal, mode common.ReleaseMode, secret string) (string, error) {+ expirationTime := time.Now().Add(accessTokenDuration)+ return generateToken(user, fmt.Sprintf(AccessTokenAudienceFmt, mode), expirationTime, []byte(secret))+}++// GenerateRefreshToken generates a refresh token for web.+func GenerateRefreshToken(user *api.Principal, mode common.ReleaseMode, secret string) (string, error) {+ expirationTime := time.Now().Add(refreshTokenDuration)+ return generateToken(user, fmt.Sprintf(RefreshTokenAudienceFmt, mode), expirationTime, []byte(secret))}// Pay attention to this function. It holds the main JWT token generation logic.func generateToken(user *api.Principal, aud string, expirationTime time.Time, secret []byte) (string, error) {// Create the JWT claims, which includes the username and expiry time.- claims := &claims{+ claims := &claimsMessage{Name: user.Name,RegisteredClaims: jwt.RegisteredClaims{Audience: jwt.ClaimStrings{aud},diff --git a/server/api/auth/config.go b/server/api/auth/config.goindex be72178c82..fff45abcd8 100644--- a/server/api/auth/config.go+++ b/server/api/auth/config.go@@ -4,11 +4,13 @@ import ("strings")-const apiPackagePrefix = "/bytebase.v1."+const (+ apiPackagePrefix = "/bytebase.v1."+)var authenticationAllowlistMethods = map[string]bool{- "AuthService/Login": true,- "GreeterService/Hello": true,+ "AuthService/Login": true,+ "AuthService/Logout": true,}var ownerAndDBAMethods = map[string]bool{diff --git a/server/api/auth/header.go b/server/api/auth/header.gonew file mode 100644index 0000000000..2fe81910aa--- /dev/null+++ b/server/api/auth/header.go@@ -0,0 +1,59 @@+package auth++import (+ "context"+ "net/http"+ "time"++ "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"+ "github.com/pkg/errors"+ "google.golang.org/protobuf/proto"+)++// GatewayResponseModifier is the mux option for modifying response header.+func GatewayResponseModifier(ctx context.Context, response http.ResponseWriter, _ proto.Message) error {+ md, ok := runtime.ServerMetadataFromContext(ctx)+ if !ok {+ return errors.Errorf("failed to get ServerMetadata from context in the gateway response modifier")+ }+ processMetadata(md, GatewayMetadataAccessTokenKey, AccessTokenCookieName, response)+ processMetadata(md, GatewayMetadataRefreshTokenKey, RefreshTokenCookieName, response)+ processMetadata(md, GatewayMetadataUserIDKey, UserIDCookieName, response)+ return nil+}++func processMetadata(md runtime.ServerMetadata, metadataKey, cookieName string, response http.ResponseWriter) {+ values := md.HeaderMD.Get(metadataKey)+ if len(values) == 0 {+ return+ }+ value := values[0]+ if value == "" {+ unsetCookie(response, cookieName)+ } else {+ setCookie(response, cookieName, value)+ }+}++func setCookie(response http.ResponseWriter, key, value string) {+ http.SetCookie(response, &http.Cookie{+ Name: key,+ Value: value,+ Expires: time.Now().Add(CookieExpDuration),+ Path: "/",+ // Http-only helps mitigate the risk of client side script accessing the protected cookie.+ HttpOnly: true,+ // For now, we allow Bytebase to run on non-https host, see https://github.com/bytebase/bytebase/issues/31+ // cookie.Secure = true+ SameSite: http.SameSiteStrictMode,+ })+}++func unsetCookie(response http.ResponseWriter, key string) {+ http.SetCookie(response, &http.Cookie{+ Name: key,+ Value: "",+ Expires: time.Unix(0, 0),+ Path: "/",+ })+}diff --git a/server/api/v1/auth_service.go b/server/api/v1/auth_service.goindex 34767b0806..5a68f48d9f 100644--- a/server/api/v1/auth_service.go+++ b/server/api/v1/auth_service.go@@ -2,10 +2,14 @@ package v1import ("context"+ "fmt""golang.org/x/crypto/bcrypt"+ "google.golang.org/grpc""google.golang.org/grpc/codes"+ "google.golang.org/grpc/metadata""google.golang.org/grpc/status"+ "google.golang.org/protobuf/types/known/emptypb""github.com/bytebase/bytebase/api"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"@@ -59,11 +63,45 @@ func (s *AuthService) Login(ctx context.Context, request *v1pb.LoginRequest) (*vreturn nil, status.Errorf(codes.NotFound, "This user %q has been deactivated by administrators", request.Email)}- accessToken, err := auth.GenerateAPIToken(user, s.profile.Mode, s.secret)- if err != nil {- return nil, status.Errorf(codes.Internal, "failed to generate API access token")+ var accessToken string+ if request.Web {+ token, err := auth.GenerateAccessToken(user, s.profile.Mode, s.secret)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to generate API access token")+ }+ accessToken = token+ refreshToken, err := auth.GenerateRefreshToken(user, s.profile.Mode, s.secret)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to generate API access token")+ }++ if err := grpc.SetHeader(ctx, metadata.New(map[string]string{+ auth.GatewayMetadataAccessTokenKey: accessToken,+ auth.GatewayMetadataRefreshTokenKey: refreshToken,+ auth.GatewayMetadataUserIDKey: fmt.Sprintf("%d", user.ID),+ })); err != nil {+ return nil, status.Errorf(codes.Internal, "failed to set grpc header, error %v", err)+ }+ } else {+ token, err := auth.GenerateAPIToken(user, s.profile.Mode, s.secret)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to generate API access token")+ }+ accessToken = token}return &v1pb.LoginResponse{Token: accessToken,}, nil}++// Logout is the auth logtou method.+func (*AuthService) Logout(ctx context.Context, _ *v1pb.LogoutRequest) (*emptypb.Empty, error) {+ if err := grpc.SetHeader(ctx, metadata.New(map[string]string{+ auth.GatewayMetadataAccessTokenKey: "",+ auth.GatewayMetadataRefreshTokenKey: "",+ auth.GatewayMetadataUserIDKey: "",+ })); err != nil {+ return nil, status.Errorf(codes.Internal, "failed to set grpc header, error %v", err)+ }+ return &emptypb.Empty{}, nil+}diff --git a/server/auth.go b/server/auth.goindex 92a5d4ff4d..fb9f037eb1 100644--- a/server/auth.go+++ b/server/auth.go@@ -15,6 +15,7 @@ import (metricAPI "github.com/bytebase/bytebase/metric""github.com/bytebase/bytebase/plugin/metric""github.com/bytebase/bytebase/plugin/vcs"+ "github.com/bytebase/bytebase/server/api/auth""github.com/bytebase/bytebase/server/component/activity")@@ -187,8 +188,8 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {})g.POST("/auth/logout", func(c echo.Context) error {- removeTokenCookie(c, accessTokenCookieName)- removeTokenCookie(c, refreshTokenCookieName)+ removeTokenCookie(c, auth.AccessTokenCookieName)+ removeTokenCookie(c, auth.RefreshTokenCookieName)removeUserCookie(c)c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)diff --git a/server/jwt.go b/server/jwt.goindex fc46786f5f..ff74a7a305 100644--- a/server/jwt.go+++ b/server/jwt.go@@ -14,43 +14,15 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/server/api/auth""github.com/bytebase/bytebase/store")const (- issuer = "bytebase"- accessTokenAudienceFmt = "bb.user.access.%s"- refreshTokenAudienceFmt = "bb.user.refresh.%s"-- // Cookie section.- accessTokenCookieName = "access-token"- refreshTokenCookieName = "refresh-token"-- // Signing key section. For now, this is only used for signing, not for verifying since we only- // have 1 version. But it will be used to maintain backward compatibility if we change the signing mechanism.- keyID = "v1"-- // Expiration section.- refreshThresholdDuration = 1 * time.Hour- accessTokenDuration = 24 * time.Hour- apiTokenDuration = 2 * time.Hour- refreshTokenDuration = 7 * 24 * time.Hour- // Make cookie expire slightly earlier than the jwt expiration. Client would be logged out if the user- // cookie expires, thus the client would always logout first before attempting to make a request with the expired jwt.- // Suppose we have a valid refresh token, we will refresh the token in 2 cases:- // 1. The access token is about to expire in <<refreshThresholdDuration>>- // 2. The access token has already expired, we refresh the token so that the ongoing request can pass through.- cookieExpDuration = refreshTokenDuration - 1*time.Minute-// Context section// The key name used to store principal id in the context// principal id is extracted from the jwt token subject field.principalIDContextKey = "principal-id"-- // Various access key / token prefix.-- // serviceAccountAccessKeyPrefix is the prefix for service account access key.- serviceAccountAccessKeyPrefix = "bbs_")// Claims creates a struct that will be encoded to a JWT.@@ -66,63 +38,25 @@ func getPrincipalIDContextKey() string {// GenerateTokensAndSetCookies generates jwt token and saves it to the http-only cookie.func GenerateTokensAndSetCookies(c echo.Context, user *api.Principal, mode common.ReleaseMode, secret string) error {- accessToken, err := generateAccessToken(user, mode, secret)+ accessToken, err := auth.GenerateAccessToken(user, mode, secret)if err != nil {return pkgerrors.Wrap(err, "failed to generate access token")}- cookieExp := time.Now().Add(cookieExpDuration)- setTokenCookie(c, accessTokenCookieName, accessToken, cookieExp)+ cookieExp := time.Now().Add(auth.CookieExpDuration)+ setTokenCookie(c, auth.AccessTokenCookieName, accessToken, cookieExp)setUserCookie(c, user, cookieExp)// We generate here a new refresh token and saving it to the cookie.- refreshToken, err := generateRefreshToken(user, mode, secret)+ refreshToken, err := auth.GenerateRefreshToken(user, mode, secret)if err != nil {return pkgerrors.Wrap(err, "failed to generate refresh token")}- setTokenCookie(c, refreshTokenCookieName, refreshToken, cookieExp)+ setTokenCookie(c, auth.RefreshTokenCookieName, refreshToken, cookieExp)return nil}-func generateAccessToken(user *api.Principal, mode common.ReleaseMode, secret string) (string, error) {- expirationTime := time.Now().Add(accessTokenDuration)- return generateToken(user, fmt.Sprintf(accessTokenAudienceFmt, mode), expirationTime, []byte(secret))-}--func generateRefreshToken(user *api.Principal, mode common.ReleaseMode, secret string) (string, error) {- expirationTime := time.Now().Add(refreshTokenDuration)- return generateToken(user, fmt.Sprintf(refreshTokenAudienceFmt, mode), expirationTime, []byte(secret))-}--// Pay attention to this function. It holds the main JWT token generation logic.-func generateToken(user *api.Principal, aud string, expirationTime time.Time, secret []byte) (string, error) {- // Create the JWT claims, which includes the username and expiry time.- claims := &Claims{- Name: user.Name,- RegisteredClaims: jwt.RegisteredClaims{- Audience: jwt.ClaimStrings{aud},- // In JWT, the expiry time is expressed as unix milliseconds.- ExpiresAt: jwt.NewNumericDate(expirationTime),- IssuedAt: jwt.NewNumericDate(time.Now()),- Issuer: issuer,- Subject: strconv.Itoa(user.ID),- },- }-- // Declare the token with the HS256 algorithm used for signing, and the claims.- token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)- token.Header["kid"] = keyID-- // Create the JWT string.- tokenString, err := token.SignedString(secret)- if err != nil {- return "", err- }-- return tokenString, nil-}-// Here we are creating a new cookie, which will store the valid JWT token.func setTokenCookie(c echo.Context, name, token string, expiration time.Time) {cookie := new(http.Cookie)@@ -184,7 +118,7 @@ func findAccessToken(c echo.Context) (string, error) {return authHeaderParts[1], nil}- cookie, err := c.Cookie(accessTokenCookieName)+ cookie, err := c.Cookie(auth.AccessTokenCookieName)if err != nil {return "", err}@@ -233,15 +167,15 @@ func JWTMiddleware(pathPrefix string, principalStore *store.Store, next echo.Hanreturn nil, pkgerrors.Errorf("unexpected access token kid=%v", t.Header["kid"])})- if !audienceContains(claims.Audience, fmt.Sprintf(accessTokenAudienceFmt, mode)) {+ if !audienceContains(claims.Audience, fmt.Sprintf(auth.AccessTokenAudienceFmt, mode)) {return echo.NewHTTPError(http.StatusUnauthorized,fmt.Sprintf("Invalid access token, audience mismatch, got %q, expected %q. you may send request to the wrong environment",claims.Audience,- fmt.Sprintf(accessTokenAudienceFmt, mode),+ fmt.Sprintf(auth.AccessTokenAudienceFmt, mode),))}- generateToken := time.Until(claims.ExpiresAt.Time) < refreshThresholdDuration+ generateToken := time.Until(claims.ExpiresAt.Time) < auth.RefreshThresholdDurationif err != nil {var ve *jwt.ValidationErrorif errors.As(err, &ve) {@@ -273,7 +207,7 @@ func JWTMiddleware(pathPrefix string, principalStore *store.Store, next echo.Hanif generateToken {generateTokenFunc := func() error {- rc, err := c.Cookie(refreshTokenCookieName)+ rc, err := c.Cookie(auth.RefreshTokenCookieName)if err != nil {return echo.NewHTTPError(http.StatusUnauthorized, "Failed to generate access token. Missing refresh token.")@@ -300,11 +234,11 @@ func JWTMiddleware(pathPrefix string, principalStore *store.Store, next echo.Hanreturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to refresh expired token. User Id %d", principalID)).SetInternal(err)}- if !audienceContains(refreshTokenClaims.Audience, fmt.Sprintf(refreshTokenAudienceFmt, mode)) {+ if !audienceContains(refreshTokenClaims.Audience, fmt.Sprintf(auth.RefreshTokenAudienceFmt, mode)) {return echo.NewHTTPError(http.StatusUnauthorized,fmt.Sprintf("Invalid refresh token, audience mismatch, got %q, expected %q. you may send request to the wrong environment",refreshTokenClaims.Audience,- fmt.Sprintf(refreshTokenAudienceFmt, mode),+ fmt.Sprintf(auth.RefreshTokenAudienceFmt, mode),))}diff --git a/server/principal.go b/server/principal.goindex 1aa982902f..1f70181934 100644--- a/server/principal.go+++ b/server/principal.go@@ -14,6 +14,9 @@ import ("github.com/bytebase/bytebase/common")+// serviceAccountAccessKeyPrefix is the prefix for service account access key.+const serviceAccountAccessKeyPrefix = "bbs_"+func (s *Server) registerPrincipalRoutes(g *echo.Group) {g.POST("/principal", func(c echo.Context) error {ctx := c.Request().Context()diff --git a/server/server.go b/server/server.goindex 4878563ea6..8811ee4dd5 100644--- a/server/server.go+++ b/server/server.go@@ -304,7 +304,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {s.grpcServer = grpc.NewServer(grpc.ChainUnaryInterceptor(authProvider.AuthenticationInterceptor, authProvider.ACLInterceptor),)- mux := runtime.NewServeMux()+ mux := runtime.NewServeMux(runtime.WithForwardResponseOption(auth.GatewayResponseModifier))v1pb.RegisterAuthServiceServer(s.grpcServer, v1.NewAuthService(s.store, s.secret, &profile))v1pb.RegisterEnvironmentServiceServer(s.grpcServer, v1.NewEnvironmentService(s.store, s.licenseService))v1pb.RegisterInstanceServiceServer(s.grpcServer, v1.NewInstanceService(s.store, s.licenseService))