From c14dce9b725b2bce69da5aa92437115b8ec59155 Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Mon, 23 Nov 2026 23:25:53 -0500 Subject: [PATCH 01/15] Vendor onboarding service proto subset Copy the GetOrCreateCLIOnboardingState RPC from saas-proto (#1455, CAS-297) into proto/onboardingservice/v1, trimmed to the fields the CLI uses. Omitted fields are reserved, so the wire format matches the server. saas-proto remains the source of truth. Generate Go code with buf (`make proto`); protoc-gen-go and protoc-gen-go-grpc are pinned as go tools. Co-Authored-By: Claude Opus 5.5 --- Makefile | 8 +- buf.gen.yaml | 10 + buf.yaml | 13 + go.mod | 7 +- go.sum | 2 + .../onboardingservice/v1/onboarding.pb.go | 418 ++++++++++++++++++ internal/onboardingservice/v1/service.pb.go | 73 +++ .../onboardingservice/v1/service_grpc.pb.go | 131 ++++++ proto/onboardingservice/v1/onboarding.proto | 79 ++++ proto/onboardingservice/v1/service.proto | 19 + 10 files changed, 758 insertions(+), 2 deletions(-) create mode 100644 buf.gen.yaml create mode 100644 buf.yaml create mode 100644 internal/onboardingservice/v1/onboarding.pb.go create mode 100644 internal/onboardingservice/v1/service.pb.go create mode 100644 internal/onboardingservice/v1/service_grpc.pb.go create mode 100644 proto/onboardingservice/v1/onboarding.proto create mode 100644 proto/onboardingservice/v1/service.proto diff --git a/Makefile b/Makefile index 073034d..03de9c5 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: all install gen build test mocks +.PHONY: all install gen proto build test mocks # Load .env file if it exists (for local development) # In CI/CD, environment variables are provided by the environment @@ -25,6 +25,12 @@ install: gen: install gen-commands -input ./temporalcloudcli/commands.yml -pkg temporalcloudcli > ./temporalcloudcli/commands.gen.go +# Regenerates the vendored onboarding service client (proto/ -> internal/). +# Requires buf on PATH; the protoc plugins are pinned as go tools in go.mod. +proto: + buf lint + buf generate + build: go build -ldflags "$(LDFLAGS)" ./cmd/temporal-cloud diff --git a/buf.gen.yaml b/buf.gen.yaml new file mode 100644 index 0000000..f3faa39 --- /dev/null +++ b/buf.gen.yaml @@ -0,0 +1,10 @@ +version: v2 +inputs: + - directory: proto +plugins: + - local: ["go", "tool", "protoc-gen-go"] + out: internal + opt: [paths=source_relative] + - local: ["go", "tool", "protoc-gen-go-grpc"] + out: internal + opt: [paths=source_relative] diff --git a/buf.yaml b/buf.yaml new file mode 100644 index 0000000..1c5534a --- /dev/null +++ b/buf.yaml @@ -0,0 +1,13 @@ +version: v2 +modules: + - path: proto +lint: + use: + - STANDARD + except: + # Names and layout mirror saas-proto, which is the source of truth. + - PACKAGE_DIRECTORY_MATCH + - RPC_REQUEST_RESPONSE_UNIQUE + - RPC_REQUEST_STANDARD_NAME + - RPC_RESPONSE_STANDARD_NAME + - SERVICE_SUFFIX diff --git a/go.mod b/go.mod index 2fac367..1cb633a 100644 --- a/go.mod +++ b/go.mod @@ -80,7 +80,12 @@ require ( golang.org/x/tools v0.51.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect + google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) -tool github.com/vektra/mockery/v3 +tool ( + github.com/vektra/mockery/v3 + google.golang.org/grpc/cmd/protoc-gen-go-grpc + google.golang.org/protobuf/cmd/protoc-gen-go +) diff --git a/go.sum b/go.sum index ec83f5e..4764b02 100644 --- a/go.sum +++ b/go.sum @@ -229,6 +229,8 @@ google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1: google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE= google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= +google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1 h1:F29+wU6Ee6qgu9TddPgooOdaqsxTMunOoj8KA5yuS5A= +google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1/go.mod h1:5KF+wpkbTSbGcR9zteSqZV6fqFOWBl4Yde8En8MryZA= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/onboardingservice/v1/onboarding.pb.go b/internal/onboardingservice/v1/onboarding.pb.go new file mode 100644 index 0000000..e3f29fa --- /dev/null +++ b/internal/onboardingservice/v1/onboarding.pb.go @@ -0,0 +1,418 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc (unknown) +// source: onboardingservice/v1/onboarding.proto + +// Vendored subset of saas-proto proto/onboardingservice/v1/onboarding.proto. +// saas-proto is the source of truth. Field names, numbers and types must match +// it exactly. Fields the CLI does not need, and that would pull in private +// saas-proto imports, are left out and reserved here; the decoder skips them as +// unknown fields. Changes must be additive and land in saas-proto first. + +package onboardingservice + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type StepType int32 + +const ( + StepType_STEP_TYPE_UNSPECIFIED StepType = 0 + StepType_STEP_TYPE_CUSTOMER_DETAILS_COLLECTION StepType = 1 + StepType_STEP_TYPE_WAIT_FOR_THROTTLE StepType = 2 + StepType_STEP_TYPE_WAIT_FOR_PAYMENT_PROVIDER_SETUP StepType = 3 + StepType_STEP_TYPE_PAYMENT_COLLECTION StepType = 4 + StepType_STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION StepType = 5 + StepType_STEP_TYPE_END_OF_FUNNEL StepType = 6 +) + +// Enum value maps for StepType. +var ( + StepType_name = map[int32]string{ + 0: "STEP_TYPE_UNSPECIFIED", + 1: "STEP_TYPE_CUSTOMER_DETAILS_COLLECTION", + 2: "STEP_TYPE_WAIT_FOR_THROTTLE", + 3: "STEP_TYPE_WAIT_FOR_PAYMENT_PROVIDER_SETUP", + 4: "STEP_TYPE_PAYMENT_COLLECTION", + 5: "STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION", + 6: "STEP_TYPE_END_OF_FUNNEL", + } + StepType_value = map[string]int32{ + "STEP_TYPE_UNSPECIFIED": 0, + "STEP_TYPE_CUSTOMER_DETAILS_COLLECTION": 1, + "STEP_TYPE_WAIT_FOR_THROTTLE": 2, + "STEP_TYPE_WAIT_FOR_PAYMENT_PROVIDER_SETUP": 3, + "STEP_TYPE_PAYMENT_COLLECTION": 4, + "STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION": 5, + "STEP_TYPE_END_OF_FUNNEL": 6, + } +) + +func (x StepType) Enum() *StepType { + p := new(StepType) + *p = x + return p +} + +func (x StepType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (StepType) Descriptor() protoreflect.EnumDescriptor { + return file_onboardingservice_v1_onboarding_proto_enumTypes[0].Descriptor() +} + +func (StepType) Type() protoreflect.EnumType { + return &file_onboardingservice_v1_onboarding_proto_enumTypes[0] +} + +func (x StepType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use StepType.Descriptor instead. +func (StepType) EnumDescriptor() ([]byte, []int) { + return file_onboardingservice_v1_onboarding_proto_rawDescGZIP(), []int{0} +} + +type OnboardingState struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Indicates the current step of the funnel the user is on + CurrentStep StepType `protobuf:"varint,1,opt,name=current_step,json=currentStep,proto3,enum=onboardingservice.v1.StepType" json:"current_step,omitempty"` + UserEmail string `protobuf:"bytes,7,opt,name=user_email,json=userEmail,proto3" json:"user_email,omitempty"` + // The Temporal Cloud user id of the user, if available. Empty if the user does not have one yet. + UserId string `protobuf:"bytes,12,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *OnboardingState) Reset() { + *x = OnboardingState{} + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *OnboardingState) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OnboardingState) ProtoMessage() {} + +func (x *OnboardingState) ProtoReflect() protoreflect.Message { + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OnboardingState.ProtoReflect.Descriptor instead. +func (*OnboardingState) Descriptor() ([]byte, []int) { + return file_onboardingservice_v1_onboarding_proto_rawDescGZIP(), []int{0} +} + +func (x *OnboardingState) GetCurrentStep() StepType { + if x != nil { + return x.CurrentStep + } + return StepType_STEP_TYPE_UNSPECIFIED +} + +func (x *OnboardingState) GetUserEmail() string { + if x != nil { + return x.UserEmail + } + return "" +} + +func (x *OnboardingState) GetUserId() string { + if x != nil { + return x.UserId + } + return "" +} + +type GetOrCreateCLIOnboardingStateRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Optional, as is every field in it; the CLI sends whatever its login provides. + CustomerDetails *CustomerDetails `protobuf:"bytes,1,opt,name=customer_details,json=customerDetails,proto3" json:"customer_details,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetOrCreateCLIOnboardingStateRequest) Reset() { + *x = GetOrCreateCLIOnboardingStateRequest{} + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetOrCreateCLIOnboardingStateRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetOrCreateCLIOnboardingStateRequest) ProtoMessage() {} + +func (x *GetOrCreateCLIOnboardingStateRequest) ProtoReflect() protoreflect.Message { + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetOrCreateCLIOnboardingStateRequest.ProtoReflect.Descriptor instead. +func (*GetOrCreateCLIOnboardingStateRequest) Descriptor() ([]byte, []int) { + return file_onboardingservice_v1_onboarding_proto_rawDescGZIP(), []int{1} +} + +func (x *GetOrCreateCLIOnboardingStateRequest) GetCustomerDetails() *CustomerDetails { + if x != nil { + return x.CustomerDetails + } + return nil +} + +type GetOrCreateCLIOnboardingStateResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + UserAlreadyExists bool `protobuf:"varint,1,opt,name=user_already_exists,json=userAlreadyExists,proto3" json:"user_already_exists,omitempty"` + // Empty if user_already_exists is true. + State *OnboardingState `protobuf:"bytes,2,opt,name=state,proto3" json:"state,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetOrCreateCLIOnboardingStateResponse) Reset() { + *x = GetOrCreateCLIOnboardingStateResponse{} + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetOrCreateCLIOnboardingStateResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetOrCreateCLIOnboardingStateResponse) ProtoMessage() {} + +func (x *GetOrCreateCLIOnboardingStateResponse) ProtoReflect() protoreflect.Message { + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetOrCreateCLIOnboardingStateResponse.ProtoReflect.Descriptor instead. +func (*GetOrCreateCLIOnboardingStateResponse) Descriptor() ([]byte, []int) { + return file_onboardingservice_v1_onboarding_proto_rawDescGZIP(), []int{2} +} + +func (x *GetOrCreateCLIOnboardingStateResponse) GetUserAlreadyExists() bool { + if x != nil { + return x.UserAlreadyExists + } + return false +} + +func (x *GetOrCreateCLIOnboardingStateResponse) GetState() *OnboardingState { + if x != nil { + return x.State + } + return nil +} + +type CustomerDetails struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The first name of the customer. + FirstName string `protobuf:"bytes,1,opt,name=first_name,json=firstName,proto3" json:"first_name,omitempty"` + // The last name of the customer. + LastName string `protobuf:"bytes,2,opt,name=last_name,json=lastName,proto3" json:"last_name,omitempty"` + // The name of the company the user is from. If empty, the server defaults to "Personal". + CompanyName string `protobuf:"bytes,3,opt,name=company_name,json=companyName,proto3" json:"company_name,omitempty"` + // The country of the user. + Country string `protobuf:"bytes,4,opt,name=country,proto3" json:"country,omitempty"` + // Indicates whether the user is interested in receiving marketing emails from Temporal + OptInMarketingEmail bool `protobuf:"varint,7,opt,name=opt_in_marketing_email,json=optInMarketingEmail,proto3" json:"opt_in_marketing_email,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CustomerDetails) Reset() { + *x = CustomerDetails{} + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CustomerDetails) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CustomerDetails) ProtoMessage() {} + +func (x *CustomerDetails) ProtoReflect() protoreflect.Message { + mi := &file_onboardingservice_v1_onboarding_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CustomerDetails.ProtoReflect.Descriptor instead. +func (*CustomerDetails) Descriptor() ([]byte, []int) { + return file_onboardingservice_v1_onboarding_proto_rawDescGZIP(), []int{3} +} + +func (x *CustomerDetails) GetFirstName() string { + if x != nil { + return x.FirstName + } + return "" +} + +func (x *CustomerDetails) GetLastName() string { + if x != nil { + return x.LastName + } + return "" +} + +func (x *CustomerDetails) GetCompanyName() string { + if x != nil { + return x.CompanyName + } + return "" +} + +func (x *CustomerDetails) GetCountry() string { + if x != nil { + return x.Country + } + return "" +} + +func (x *CustomerDetails) GetOptInMarketingEmail() bool { + if x != nil { + return x.OptInMarketingEmail + } + return false +} + +var File_onboardingservice_v1_onboarding_proto protoreflect.FileDescriptor + +const file_onboardingservice_v1_onboarding_proto_rawDesc = "" + + "\n" + + "%onboardingservice/v1/onboarding.proto\x12\x14onboardingservice.v1\"\xeb\x02\n" + + "\x0fOnboardingState\x12A\n" + + "\fcurrent_step\x18\x01 \x01(\x0e2\x1e.onboardingservice.v1.StepTypeR\vcurrentStep\x12\x1d\n" + + "\n" + + "user_email\x18\a \x01(\tR\tuserEmail\x12\x17\n" + + "\auser_id\x18\f \x01(\tR\x06userIdJ\x04\b\x02\x10\aJ\x04\b\b\x10\fR\x1bcustomer_details_collectionR\x11wait_for_throttleR\fstripe_setupR stripe_setup_intent_confirmationR\x19wait_for_account_creationR\x13eligible_promotionsR\x16eligible_billing_plansR\x0ftarget_sku_typeR\x18billing_provider_details\"x\n" + + "$GetOrCreateCLIOnboardingStateRequest\x12P\n" + + "\x10customer_details\x18\x01 \x01(\v2%.onboardingservice.v1.CustomerDetailsR\x0fcustomerDetails\"\x94\x01\n" + + "%GetOrCreateCLIOnboardingStateResponse\x12.\n" + + "\x13user_already_exists\x18\x01 \x01(\bR\x11userAlreadyExists\x12;\n" + + "\x05state\x18\x02 \x01(\v2%.onboardingservice.v1.OnboardingStateR\x05state\"\xf2\x01\n" + + "\x0fCustomerDetails\x12\x1d\n" + + "\n" + + "first_name\x18\x01 \x01(\tR\tfirstName\x12\x1b\n" + + "\tlast_name\x18\x02 \x01(\tR\blastName\x12!\n" + + "\fcompany_name\x18\x03 \x01(\tR\vcompanyName\x12\x18\n" + + "\acountry\x18\x04 \x01(\tR\acountry\x123\n" + + "\x16opt_in_marketing_email\x18\a \x01(\bR\x13optInMarketingEmailJ\x04\b\x05\x10\x06J\x04\b\x06\x10\aJ\x04\b\b\x10\tR\x16agree_terms_of_serviceR\apurpose*\x88\x02\n" + + "\bStepType\x12\x19\n" + + "\x15STEP_TYPE_UNSPECIFIED\x10\x00\x12)\n" + + "%STEP_TYPE_CUSTOMER_DETAILS_COLLECTION\x10\x01\x12\x1f\n" + + "\x1bSTEP_TYPE_WAIT_FOR_THROTTLE\x10\x02\x12-\n" + + ")STEP_TYPE_WAIT_FOR_PAYMENT_PROVIDER_SETUP\x10\x03\x12 \n" + + "\x1cSTEP_TYPE_PAYMENT_COLLECTION\x10\x04\x12'\n" + + "#STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION\x10\x05\x12\x1b\n" + + "\x17STEP_TYPE_END_OF_FUNNEL\x10\x06BQZOgithub.com/temporalio/cloud-cli/internal/onboardingservice/v1;onboardingserviceb\x06proto3" + +var ( + file_onboardingservice_v1_onboarding_proto_rawDescOnce sync.Once + file_onboardingservice_v1_onboarding_proto_rawDescData []byte +) + +func file_onboardingservice_v1_onboarding_proto_rawDescGZIP() []byte { + file_onboardingservice_v1_onboarding_proto_rawDescOnce.Do(func() { + file_onboardingservice_v1_onboarding_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_onboardingservice_v1_onboarding_proto_rawDesc), len(file_onboardingservice_v1_onboarding_proto_rawDesc))) + }) + return file_onboardingservice_v1_onboarding_proto_rawDescData +} + +var file_onboardingservice_v1_onboarding_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_onboardingservice_v1_onboarding_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_onboardingservice_v1_onboarding_proto_goTypes = []any{ + (StepType)(0), // 0: onboardingservice.v1.StepType + (*OnboardingState)(nil), // 1: onboardingservice.v1.OnboardingState + (*GetOrCreateCLIOnboardingStateRequest)(nil), // 2: onboardingservice.v1.GetOrCreateCLIOnboardingStateRequest + (*GetOrCreateCLIOnboardingStateResponse)(nil), // 3: onboardingservice.v1.GetOrCreateCLIOnboardingStateResponse + (*CustomerDetails)(nil), // 4: onboardingservice.v1.CustomerDetails +} +var file_onboardingservice_v1_onboarding_proto_depIdxs = []int32{ + 0, // 0: onboardingservice.v1.OnboardingState.current_step:type_name -> onboardingservice.v1.StepType + 4, // 1: onboardingservice.v1.GetOrCreateCLIOnboardingStateRequest.customer_details:type_name -> onboardingservice.v1.CustomerDetails + 1, // 2: onboardingservice.v1.GetOrCreateCLIOnboardingStateResponse.state:type_name -> onboardingservice.v1.OnboardingState + 3, // [3:3] is the sub-list for method output_type + 3, // [3:3] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name +} + +func init() { file_onboardingservice_v1_onboarding_proto_init() } +func file_onboardingservice_v1_onboarding_proto_init() { + if File_onboardingservice_v1_onboarding_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_onboardingservice_v1_onboarding_proto_rawDesc), len(file_onboardingservice_v1_onboarding_proto_rawDesc)), + NumEnums: 1, + NumMessages: 4, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_onboardingservice_v1_onboarding_proto_goTypes, + DependencyIndexes: file_onboardingservice_v1_onboarding_proto_depIdxs, + EnumInfos: file_onboardingservice_v1_onboarding_proto_enumTypes, + MessageInfos: file_onboardingservice_v1_onboarding_proto_msgTypes, + }.Build() + File_onboardingservice_v1_onboarding_proto = out.File + file_onboardingservice_v1_onboarding_proto_goTypes = nil + file_onboardingservice_v1_onboarding_proto_depIdxs = nil +} diff --git a/internal/onboardingservice/v1/service.pb.go b/internal/onboardingservice/v1/service.pb.go new file mode 100644 index 0000000..5df1eaa --- /dev/null +++ b/internal/onboardingservice/v1/service.pb.go @@ -0,0 +1,73 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc (unknown) +// source: onboardingservice/v1/service.proto + +// Vendored subset of saas-proto proto/onboardingservice/v1/service.proto. +// saas-proto is the source of truth. Keep the package, service, RPC and message +// names identical to it: they form the gRPC method path on the wire. Only the +// RPCs the CLI calls are copied here. Changes must be additive and land in +// saas-proto first. + +package onboardingservice + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +var File_onboardingservice_v1_service_proto protoreflect.FileDescriptor + +const file_onboardingservice_v1_service_proto_rawDesc = "" + + "\n" + + "\"onboardingservice/v1/service.proto\x12\x14onboardingservice.v1\x1a%onboardingservice/v1/onboarding.proto2\xb0\x01\n" + + "\x11OnboardingService\x12\x9a\x01\n" + + "\x1dGetOrCreateCLIOnboardingState\x12:.onboardingservice.v1.GetOrCreateCLIOnboardingStateRequest\x1a;.onboardingservice.v1.GetOrCreateCLIOnboardingStateResponse\"\x00BQZOgithub.com/temporalio/cloud-cli/internal/onboardingservice/v1;onboardingserviceb\x06proto3" + +var file_onboardingservice_v1_service_proto_goTypes = []any{ + (*GetOrCreateCLIOnboardingStateRequest)(nil), // 0: onboardingservice.v1.GetOrCreateCLIOnboardingStateRequest + (*GetOrCreateCLIOnboardingStateResponse)(nil), // 1: onboardingservice.v1.GetOrCreateCLIOnboardingStateResponse +} +var file_onboardingservice_v1_service_proto_depIdxs = []int32{ + 0, // 0: onboardingservice.v1.OnboardingService.GetOrCreateCLIOnboardingState:input_type -> onboardingservice.v1.GetOrCreateCLIOnboardingStateRequest + 1, // 1: onboardingservice.v1.OnboardingService.GetOrCreateCLIOnboardingState:output_type -> onboardingservice.v1.GetOrCreateCLIOnboardingStateResponse + 1, // [1:2] is the sub-list for method output_type + 0, // [0:1] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_onboardingservice_v1_service_proto_init() } +func file_onboardingservice_v1_service_proto_init() { + if File_onboardingservice_v1_service_proto != nil { + return + } + file_onboardingservice_v1_onboarding_proto_init() + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_onboardingservice_v1_service_proto_rawDesc), len(file_onboardingservice_v1_service_proto_rawDesc)), + NumEnums: 0, + NumMessages: 0, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_onboardingservice_v1_service_proto_goTypes, + DependencyIndexes: file_onboardingservice_v1_service_proto_depIdxs, + }.Build() + File_onboardingservice_v1_service_proto = out.File + file_onboardingservice_v1_service_proto_goTypes = nil + file_onboardingservice_v1_service_proto_depIdxs = nil +} diff --git a/internal/onboardingservice/v1/service_grpc.pb.go b/internal/onboardingservice/v1/service_grpc.pb.go new file mode 100644 index 0000000..8894c77 --- /dev/null +++ b/internal/onboardingservice/v1/service_grpc.pb.go @@ -0,0 +1,131 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.5.1 +// - protoc (unknown) +// source: onboardingservice/v1/service.proto + +// Vendored subset of saas-proto proto/onboardingservice/v1/service.proto. +// saas-proto is the source of truth. Keep the package, service, RPC and message +// names identical to it: they form the gRPC method path on the wire. Only the +// RPCs the CLI calls are copied here. Changes must be additive and land in +// saas-proto first. + +package onboardingservice + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + OnboardingService_GetOrCreateCLIOnboardingState_FullMethodName = "/onboardingservice.v1.OnboardingService/GetOrCreateCLIOnboardingState" +) + +// OnboardingServiceClient is the client API for OnboardingService service. +// +// 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 OnboardingServiceClient interface { + // The endpoint the Temporal CLI signup command polls. + // Same contract as GetOrCreateOnboardingState for a CLI-started session. + GetOrCreateCLIOnboardingState(ctx context.Context, in *GetOrCreateCLIOnboardingStateRequest, opts ...grpc.CallOption) (*GetOrCreateCLIOnboardingStateResponse, error) +} + +type onboardingServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewOnboardingServiceClient(cc grpc.ClientConnInterface) OnboardingServiceClient { + return &onboardingServiceClient{cc} +} + +func (c *onboardingServiceClient) GetOrCreateCLIOnboardingState(ctx context.Context, in *GetOrCreateCLIOnboardingStateRequest, opts ...grpc.CallOption) (*GetOrCreateCLIOnboardingStateResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetOrCreateCLIOnboardingStateResponse) + err := c.cc.Invoke(ctx, OnboardingService_GetOrCreateCLIOnboardingState_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// OnboardingServiceServer is the server API for OnboardingService service. +// All implementations must embed UnimplementedOnboardingServiceServer +// for forward compatibility. +type OnboardingServiceServer interface { + // The endpoint the Temporal CLI signup command polls. + // Same contract as GetOrCreateOnboardingState for a CLI-started session. + GetOrCreateCLIOnboardingState(context.Context, *GetOrCreateCLIOnboardingStateRequest) (*GetOrCreateCLIOnboardingStateResponse, error) + mustEmbedUnimplementedOnboardingServiceServer() +} + +// UnimplementedOnboardingServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedOnboardingServiceServer struct{} + +func (UnimplementedOnboardingServiceServer) GetOrCreateCLIOnboardingState(context.Context, *GetOrCreateCLIOnboardingStateRequest) (*GetOrCreateCLIOnboardingStateResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetOrCreateCLIOnboardingState not implemented") +} +func (UnimplementedOnboardingServiceServer) mustEmbedUnimplementedOnboardingServiceServer() {} +func (UnimplementedOnboardingServiceServer) testEmbeddedByValue() {} + +// UnsafeOnboardingServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to OnboardingServiceServer will +// result in compilation errors. +type UnsafeOnboardingServiceServer interface { + mustEmbedUnimplementedOnboardingServiceServer() +} + +func RegisterOnboardingServiceServer(s grpc.ServiceRegistrar, srv OnboardingServiceServer) { + // If the following call pancis, it indicates UnimplementedOnboardingServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&OnboardingService_ServiceDesc, srv) +} + +func _OnboardingService_GetOrCreateCLIOnboardingState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetOrCreateCLIOnboardingStateRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OnboardingServiceServer).GetOrCreateCLIOnboardingState(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OnboardingService_GetOrCreateCLIOnboardingState_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OnboardingServiceServer).GetOrCreateCLIOnboardingState(ctx, req.(*GetOrCreateCLIOnboardingStateRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// OnboardingService_ServiceDesc is the grpc.ServiceDesc for OnboardingService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var OnboardingService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "onboardingservice.v1.OnboardingService", + HandlerType: (*OnboardingServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetOrCreateCLIOnboardingState", + Handler: _OnboardingService_GetOrCreateCLIOnboardingState_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "onboardingservice/v1/service.proto", +} diff --git a/proto/onboardingservice/v1/onboarding.proto b/proto/onboardingservice/v1/onboarding.proto new file mode 100644 index 0000000..5daf202 --- /dev/null +++ b/proto/onboardingservice/v1/onboarding.proto @@ -0,0 +1,79 @@ +syntax = "proto3"; + +// Vendored subset of saas-proto proto/onboardingservice/v1/onboarding.proto. +// saas-proto is the source of truth. Field names, numbers and types must match +// it exactly. Fields the CLI does not need, and that would pull in private +// saas-proto imports, are left out and reserved here; the decoder skips them as +// unknown fields. Changes must be additive and land in saas-proto first. +package onboardingservice.v1; + +option go_package = "github.com/temporalio/cloud-cli/internal/onboardingservice/v1;onboardingservice"; + +enum StepType { + STEP_TYPE_UNSPECIFIED = 0; + STEP_TYPE_CUSTOMER_DETAILS_COLLECTION = 1; + STEP_TYPE_WAIT_FOR_THROTTLE = 2; + STEP_TYPE_WAIT_FOR_PAYMENT_PROVIDER_SETUP = 3; + STEP_TYPE_PAYMENT_COLLECTION = 4; + STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION = 5; + STEP_TYPE_END_OF_FUNNEL = 6; +} + +message OnboardingState { + // Omitted from this copy; the CLI polls on current_step only: + // 2 customer_details_collection + // 3 wait_for_throttle + // 4 stripe_setup + // 5 stripe_setup_intent_confirmation (Stripe client secret) + // 6 wait_for_account_creation + // 8 eligible_promotions + // 9 eligible_billing_plans (private services.saasapi.ui.billingplan.v1 import) + // 10 target_sku_type (temporal.api.cloud.account.beta import) + // 11 billing_provider_details (private api.uiservice.v1 import) + reserved 2 to 6, 8 to 11; + reserved "customer_details_collection", "wait_for_throttle", "stripe_setup", + "stripe_setup_intent_confirmation", "wait_for_account_creation", "eligible_promotions", + "eligible_billing_plans", "target_sku_type", "billing_provider_details"; + + // Indicates the current step of the funnel the user is on + StepType current_step = 1; + + string user_email = 7; + + // The Temporal Cloud user id of the user, if available. Empty if the user does not have one yet. + string user_id = 12; +} + +message GetOrCreateCLIOnboardingStateRequest { + // Optional, as is every field in it; the CLI sends whatever its login provides. + CustomerDetails customer_details = 1; +} + +message GetOrCreateCLIOnboardingStateResponse { + bool user_already_exists = 1; + + // Empty if user_already_exists is true. + OnboardingState state = 2; +} + +message CustomerDetails { + // Omitted from this copy: 6 agree_terms_of_service and 8 purpose (both deprecated upstream). + // 5 was "Industry", removed upstream. + reserved 5, 6, 8; + reserved "agree_terms_of_service", "purpose"; + + // The first name of the customer. + string first_name = 1; + + // The last name of the customer. + string last_name = 2; + + // The name of the company the user is from. If empty, the server defaults to "Personal". + string company_name = 3; + + // The country of the user. + string country = 4; + + // Indicates whether the user is interested in receiving marketing emails from Temporal + bool opt_in_marketing_email = 7; +} diff --git a/proto/onboardingservice/v1/service.proto b/proto/onboardingservice/v1/service.proto new file mode 100644 index 0000000..03e869b --- /dev/null +++ b/proto/onboardingservice/v1/service.proto @@ -0,0 +1,19 @@ +syntax = "proto3"; + +// Vendored subset of saas-proto proto/onboardingservice/v1/service.proto. +// saas-proto is the source of truth. Keep the package, service, RPC and message +// names identical to it: they form the gRPC method path on the wire. Only the +// RPCs the CLI calls are copied here. Changes must be additive and land in +// saas-proto first. +package onboardingservice.v1; + +option go_package = "github.com/temporalio/cloud-cli/internal/onboardingservice/v1;onboardingservice"; + +import "onboardingservice/v1/onboarding.proto"; + +service OnboardingService { + // The endpoint the Temporal CLI signup command polls. + // Same contract as GetOrCreateOnboardingState for a CLI-started session. + rpc GetOrCreateCLIOnboardingState(GetOrCreateCLIOnboardingStateRequest) returns (GetOrCreateCLIOnboardingStateResponse) { + } +} From 2aec2beb5b7b5a40c853f4a6dbf5e9990125363c Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Mon, 23 Nov 2026 23:25:53 -0500 Subject: [PATCH 02/15] Add `temporal cloud signup` prototype Log in to Auth0 with the onboarding audience, call GetOrCreateCLIOnboardingState, and poll until onboarding completes. The sign-up token stays in memory; the user runs `temporal cloud login` afterwards. - --login-method google|microsoft|password, or an arrow-key picker in an interactive terminal. Without a TTY, Auth0 shows its own picker. - Login prompts now go to stderr so -o json output stays clean. - --disable-pop-up now prints the URL without opening a browser. - The command is hidden from help until the prod handler ships. Co-Authored-By: Claude Opus 5.5 --- internal/onboarding/wait.go | 116 ++++++++++++++ internal/onboarding/wait_test.go | 140 +++++++++++++++++ temporalcloudcli/commands.gen.go | 51 +++++++ temporalcloudcli/commands.login.go | 14 +- temporalcloudcli/commands.signup.go | 184 +++++++++++++++++++++++ temporalcloudcli/commands.yml | 69 +++++++++ temporalcloudcli/oauth.go | 16 +- temporalcloudcli/prompter/select.go | 145 ++++++++++++++++++ temporalcloudcli/prompter/select_test.go | 57 +++++++ 9 files changed, 785 insertions(+), 7 deletions(-) create mode 100644 internal/onboarding/wait.go create mode 100644 internal/onboarding/wait_test.go create mode 100644 temporalcloudcli/commands.signup.go create mode 100644 temporalcloudcli/prompter/select.go create mode 100644 temporalcloudcli/prompter/select_test.go diff --git a/internal/onboarding/wait.go b/internal/onboarding/wait.go new file mode 100644 index 0000000..bf0b0e7 --- /dev/null +++ b/internal/onboarding/wait.go @@ -0,0 +1,116 @@ +// Package onboarding polls the Temporal Cloud onboarding service until a +// CLI-started sign-up is complete. +package onboarding + +import ( + "context" + "errors" + "fmt" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + onboardingservice "github.com/temporalio/cloud-cli/internal/onboardingservice/v1" +) + +// Client is the subset of the onboarding service the CLI calls. +type Client interface { + GetOrCreateCLIOnboardingState( + ctx context.Context, + in *onboardingservice.GetOrCreateCLIOnboardingStateRequest, + opts ...grpc.CallOption, + ) (*onboardingservice.GetOrCreateCLIOnboardingStateResponse, error) +} + +// PollConfig controls the polling backoff. It mirrors the get-cloud website: +// a fixed interval for the first FastAttempts polls, then doubling up to +// MaxInterval. +type PollConfig struct { + Interval time.Duration + MaxInterval time.Duration + FastAttempts int +} + +// DefaultPollConfig matches the website's waitForStep: 1s for 10 polls, then +// doubling to a 30s cap. +var DefaultPollConfig = PollConfig{ + Interval: time.Second, + MaxInterval: 30 * time.Second, + FastAttempts: 10, +} + +// IsComplete reports whether sign-up has finished, either just now or earlier. +func IsComplete(resp *onboardingservice.GetOrCreateCLIOnboardingStateResponse) bool { + return resp.GetUserAlreadyExists() || + resp.GetState().GetCurrentStep() == onboardingservice.StepType_STEP_TYPE_END_OF_FUNNEL +} + +// Wait calls GetOrCreateCLIOnboardingState until sign-up is complete, ctx is +// done, or the service returns an error that is not worth retrying. The first +// call creates the onboarding session; the rest observe it. onStep, if set, is +// called each time the reported step changes. +func Wait( + ctx context.Context, + client Client, + req *onboardingservice.GetOrCreateCLIOnboardingStateRequest, + cfg PollConfig, + onStep func(onboardingservice.StepType), +) (*onboardingservice.GetOrCreateCLIOnboardingStateResponse, error) { + interval := cfg.Interval + lastStep := onboardingservice.StepType(-1) + + for attempt := 1; ; attempt++ { + resp, err := client.GetOrCreateCLIOnboardingState(ctx, req) + switch { + case ctx.Err() != nil: + return nil, waitError(ctx, lastStep) + case err == nil: + if IsComplete(resp) { + return resp, nil + } + if step := resp.GetState().GetCurrentStep(); step != lastStep { + lastStep = step + if onStep != nil { + onStep(step) + } + } + case !isRetryable(err): + return nil, fmt.Errorf("failed to get onboarding state: %w", err) + } + + if attempt > cfg.FastAttempts { + interval = min(interval*2, cfg.MaxInterval) + } + timer := time.NewTimer(interval) + select { + case <-ctx.Done(): + timer.Stop() + return nil, waitError(ctx, lastStep) + case <-timer.C: + } + } +} + +// isRetryable covers transient transport failures and the service's per-email +// rate limit. Anything else (auth, allow list, invalid idp) will not change on +// retry. +func isRetryable(err error) bool { + switch status.Code(err) { + case codes.Unavailable, codes.ResourceExhausted: + return true + default: + return false + } +} + +func waitError(ctx context.Context, lastStep onboardingservice.StepType) error { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + if lastStep < 0 { + return errors.New("timed out waiting for onboarding to start") + } + return fmt.Errorf("timed out waiting for onboarding to complete (last step: %s)", lastStep) + } + return ctx.Err() +} diff --git a/internal/onboarding/wait_test.go b/internal/onboarding/wait_test.go new file mode 100644 index 0000000..b7ba8bd --- /dev/null +++ b/internal/onboarding/wait_test.go @@ -0,0 +1,140 @@ +package onboarding_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/temporalio/cloud-cli/internal/onboarding" + onboardingservice "github.com/temporalio/cloud-cli/internal/onboardingservice/v1" +) + +type result struct { + resp *onboardingservice.GetOrCreateCLIOnboardingStateResponse + err error +} + +// fakeClient returns scripted results in order, repeating the last one. +type fakeClient struct { + results []result + calls int +} + +func (f *fakeClient) GetOrCreateCLIOnboardingState( + context.Context, *onboardingservice.GetOrCreateCLIOnboardingStateRequest, ...grpc.CallOption, +) (*onboardingservice.GetOrCreateCLIOnboardingStateResponse, error) { + r := f.results[min(f.calls, len(f.results)-1)] + f.calls++ + return r.resp, r.err +} + +func atStep(step onboardingservice.StepType) result { + return result{resp: &onboardingservice.GetOrCreateCLIOnboardingStateResponse{ + State: &onboardingservice.OnboardingState{CurrentStep: step}, + }} +} + +var fastPoll = onboarding.PollConfig{Interval: time.Millisecond, MaxInterval: 2 * time.Millisecond, FastAttempts: 2} + +func TestWait(t *testing.T) { + alreadyExists := result{resp: &onboardingservice.GetOrCreateCLIOnboardingStateResponse{UserAlreadyExists: true}} + done := atStep(onboardingservice.StepType_STEP_TYPE_END_OF_FUNNEL) + creating := atStep(onboardingservice.StepType_STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION) + + tests := []struct { + name string + results []result + timeout time.Duration + expectedResp *onboardingservice.GetOrCreateCLIOnboardingStateResponse + expectedErr string + expectedCalls int + expectedSteps []onboardingservice.StepType + }{ + { + name: "user already exists returns immediately", + results: []result{alreadyExists}, + expectedResp: alreadyExists.resp, + expectedCalls: 1, + }, + { + name: "polls until end of funnel and reports each step once", + results: []result{creating, creating, creating, done}, + expectedResp: done.resp, + expectedCalls: 4, + expectedSteps: []onboardingservice.StepType{onboardingservice.StepType_STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION}, + }, + { + name: "retries unavailable and rate limited", + results: []result{ + {err: status.Error(codes.Unavailable, "down")}, + {err: status.Error(codes.ResourceExhausted, "slow down")}, + done, + }, + expectedResp: done.resp, + expectedCalls: 3, + }, + { + name: "stops on permission denied", + results: []result{{err: status.Error(codes.PermissionDenied, "user not allowed")}}, + expectedErr: "failed to get onboarding state: rpc error: code = PermissionDenied desc = user not allowed", + expectedCalls: 1, + }, + { + name: "times out with the last step", + results: []result{creating}, + timeout: 20 * time.Millisecond, + expectedErr: "timed out waiting for onboarding to complete (last step: STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION)", + expectedSteps: []onboardingservice.StepType{onboardingservice.StepType_STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION}, + }, + { + name: "times out before any state", + results: []result{{err: status.Error(codes.Unavailable, "down")}}, + timeout: 20 * time.Millisecond, + expectedErr: "timed out waiting for onboarding to start", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctx := context.Background() + if tt.timeout > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, tt.timeout) + defer cancel() + } + client := &fakeClient{results: tt.results} + var steps []onboardingservice.StepType + + resp, err := onboarding.Wait(ctx, client, &onboardingservice.GetOrCreateCLIOnboardingStateRequest{}, fastPoll, + func(s onboardingservice.StepType) { steps = append(steps, s) }) + + if tt.expectedErr != "" { + require.EqualError(t, err, tt.expectedErr) + } else { + require.NoError(t, err) + assert.Equal(t, tt.expectedResp, resp) + } + if tt.expectedCalls > 0 { + assert.Equal(t, tt.expectedCalls, client.calls) + } + assert.Equal(t, tt.expectedSteps, steps) + }) + } +} + +func TestWait_Canceled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + _, err := onboarding.Wait(ctx, &fakeClient{results: []result{atStep(onboardingservice.StepType_STEP_TYPE_UNSPECIFIED)}}, + &onboardingservice.GetOrCreateCLIOnboardingStateRequest{}, fastPoll, nil) + + require.True(t, errors.Is(err, context.Canceled)) +} diff --git a/temporalcloudcli/commands.gen.go b/temporalcloudcli/commands.gen.go index 0c4edd8..127a845 100644 --- a/temporalcloudcli/commands.gen.go +++ b/temporalcloudcli/commands.gen.go @@ -309,6 +309,7 @@ func NewCloudCommand(cctx *CommandContext) *CloudCommand { s.Command.AddCommand(&NewCloudProjectCommand(cctx, &s).Command) s.Command.AddCommand(&NewCloudRegionCommand(cctx, &s).Command) s.Command.AddCommand(&NewCloudServiceAccountCommand(cctx, &s).Command) + s.Command.AddCommand(&NewCloudSignupCommand(cctx, &s).Command) s.Command.AddCommand(&NewCloudUserCommand(cctx, &s).Command) s.Command.AddCommand(&NewCloudUserGroupCommand(cctx, &s).Command) s.Command.AddCommand(&NewCloudWhoamiCommand(cctx, &s).Command) @@ -6307,6 +6308,56 @@ func NewCloudServiceAccountUpdateCommand(cctx *CommandContext, parent *CloudServ return &s } +type CloudSignupCommand struct { + Parent *CloudCommand + Command cobra.Command + Domain string + Audience string + LoginMethod cliext.FlagStringEnum + ClientId string + RedirectUrl string + OnboardingAddress string + OnboardingInsecure bool + NoWait bool +} + +func NewCloudSignupCommand(cctx *CommandContext, parent *CloudCommand) *CloudSignupCommand { + var s CloudSignupCommand + s.Parent = parent + s.Command.DisableFlagsInUseLine = true + s.Command.Use = "signup [flags]" + s.Command.Short = "Sign up for Temporal Cloud (prototype)" + if hasHighlighting { + s.Command.Long = "Sign up for Temporal Cloud from the terminal.\n\nThis command opens your default browser to authenticate, then starts or\nresumes your Temporal Cloud onboarding. The sign-up credential is kept in\nmemory only and is not written to your profile.\n\nExample:\n\n\x1b[1mtemporal cloud signup\x1b[0m" + } else { + s.Command.Long = "Sign up for Temporal Cloud from the terminal.\n\nThis command opens your default browser to authenticate, then starts or\nresumes your Temporal Cloud onboarding. The sign-up credential is kept in\nmemory only and is not written to your profile.\n\nExample:\n\n```\ntemporal cloud signup\n```" + } + s.Command.Args = cobra.NoArgs + s.Command.Flags().StringVar(&s.Domain, "domain", "login.tmprl.cloud", "Authentication domain for the OAuth provider.") + _ = s.Command.Flags().MarkHidden("domain") + s.Command.Flags().StringVar(&s.Audience, "audience", "https://onboarding.tmprl.cloud", "OAuth audience parameter for the sign-up token.") + _ = s.Command.Flags().MarkHidden("audience") + s.LoginMethod = cliext.NewFlagStringEnum([]string{"google", "microsoft", "password"}, "") + s.Command.Flags().Var(&s.LoginMethod, "login-method", "Login method to use, instead of choosing one interactively. Accepted values: google, microsoft, password.") + s.Command.Flags().StringVar(&s.ClientId, "client-id", "Cd2erICRRO9hzuGeoQyqO9iPfiCgCvMZ", "OAuth client identifier for authentication.") + _ = s.Command.Flags().MarkHidden("client-id") + s.Command.Flags().StringVar(&s.RedirectUrl, "redirect-url", "http://127.0.0.1:56628/callback", "Redirect URL for OAuth authentication flow.") + _ = s.Command.Flags().MarkHidden("redirect-url") + s.Command.Flags().StringVar(&s.OnboardingAddress, "onboarding-address", "onboarding.tmprl.cloud:443", "host:port of the Temporal Cloud onboarding service.") + _ = s.Command.Flags().MarkHidden("onboarding-address") + s.Command.Flags().BoolVar(&s.OnboardingInsecure, "onboarding-insecure", false, "Connect to the onboarding service without TLS. For local development only.") + _ = s.Command.Flags().MarkHidden("onboarding-insecure") + s.Command.Flags().BoolVar(&s.NoWait, "no-wait", false, "Return the current onboarding state without waiting. Prototype only.") + _ = s.Command.Flags().MarkHidden("no-wait") + s.Command.Run = func(c *cobra.Command, args []string) { + if err := s.run(cctx, args); err != nil { + cctx.Options.Fail(err) + } + } + s.initCommand(cctx) + return &s +} + type CloudUserCommand struct { Parent *CloudCommand Command cobra.Command diff --git a/temporalcloudcli/commands.login.go b/temporalcloudcli/commands.login.go index f2a1e26..8918376 100644 --- a/temporalcloudcli/commands.login.go +++ b/temporalcloudcli/commands.login.go @@ -37,7 +37,7 @@ func (c *CloudLoginCommand) run(cctx *CommandContext, _ []string) error { } } - oauthToken, err := Login(cctx, oauthConfig.ClientConfig, oauth2.SetAuthURLParam("audience", c.Audience)) + oauthToken, err := Login(cctx, oauthConfig.ClientConfig, !c.Parent.DisablePopUp, oauth2.SetAuthURLParam("audience", c.Audience)) if err != nil { return fmt.Errorf("failed to login: %w", err) } @@ -73,19 +73,25 @@ func parseURL(s string) (*url.URL, error) { } func (c *CloudLoginCommand) generateOauthClientConfig() (*oauth2.Config, error) { - domainURL, err := parseURL(c.Domain) + return newOAuthClientConfig(c.Domain, c.ClientId, c.RedirectUrl) +} + +// newOAuthClientConfig builds the Auth0 authorization-code (PKCE) client config +// shared by `cloud login` and `cloud signup`. +func newOAuthClientConfig(domain, clientID, redirectURL string) (*oauth2.Config, error) { + domainURL, err := parseURL(domain) if err != nil { return nil, fmt.Errorf("failed to parse domain: %w", err) } return &oauth2.Config{ - ClientID: c.ClientId, + ClientID: clientID, Endpoint: oauth2.Endpoint{ AuthURL: domainURL.JoinPath("authorize").String(), TokenURL: domainURL.JoinPath("oauth", "token").String(), AuthStyle: oauth2.AuthStyleInParams, }, - RedirectURL: c.RedirectUrl, + RedirectURL: redirectURL, Scopes: []string{"openid", "profile", "user", "offline_access"}, }, nil } diff --git a/temporalcloudcli/commands.signup.go b/temporalcloudcli/commands.signup.go new file mode 100644 index 0000000..fe76712 --- /dev/null +++ b/temporalcloudcli/commands.signup.go @@ -0,0 +1,184 @@ +package temporalcloudcli + +import ( + "context" + "crypto/tls" + "fmt" + + "golang.org/x/oauth2" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" + + "github.com/temporalio/cloud-cli/internal/onboarding" + onboardingservice "github.com/temporalio/cloud-cli/internal/onboardingservice/v1" + "github.com/temporalio/cloud-cli/temporalcloudcli/internal/printer" + cliprompter "github.com/temporalio/cloud-cli/temporalcloudcli/prompter" +) + +// initCommand hides the command from help while it is a prototype: the prod +// onboarding service does not serve this RPC yet. Remove before launch. +func (c *CloudSignupCommand) initCommand(*CommandContext) { + c.Command.Hidden = true +} + +// AIDEV-NOTE: Prototype. The sign-up token (aud=onboarding) is kept in memory +// only and never written to the profile: storing it in [oauth] would make every +// other command send an onboarding-audience token to saas-api. The saas-api +// login that ends sign-up is a separate step once onboarding is complete. +func (c *CloudSignupCommand) run(cctx *CommandContext, _ []string) error { + oauthConfig, err := newOAuthClientConfig(c.Domain, c.ClientId, c.RedirectUrl) + if err != nil { + return fmt.Errorf("failed to generate OAuth client config: %w", err) + } + + connection, err := c.chooseLoginMethod(cctx) + if err != nil { + return err + } + authParams := append([]oauth2.AuthCodeOption{oauth2.SetAuthURLParam("audience", c.Audience)}, c.connectionAuthParams(connection)...) + token, err := Login(cctx, oauthConfig, !c.Parent.DisablePopUp, authParams...) + if err != nil { + return fmt.Errorf("failed to login: %w", err) + } + + conn, err := c.dialOnboarding(oauthConfig.TokenSource(cctx, token)) + if err != nil { + return err + } + defer conn.Close() + + client := onboardingservice.NewOnboardingServiceClient(conn) + req := &onboardingservice.GetOrCreateCLIOnboardingStateRequest{} + var resp *onboardingservice.GetOrCreateCLIOnboardingStateResponse + if c.NoWait { + resp, err = client.GetOrCreateCLIOnboardingState(cctx, req) + if err != nil { + return fmt.Errorf("failed to get onboarding state: %w", err) + } + } else { + // Waits until provisioning finishes or the command is canceled; the global + // --command-timeout, when set, also bounds this. + resp, err = onboarding.Wait(cctx, client, req, onboarding.DefaultPollConfig, func(step onboardingservice.StepType) { + if !cctx.JSONOutput { + cctx.Printer.Printlnf("Waiting for your account (step: %s)...", step) + } + }) + if err != nil { + return err + } + } + + if cctx.JSONOutput { + return cctx.Printer.PrintStructured(resp, printer.StructuredOptions{}) + } + switch { + case resp.GetUserAlreadyExists(): + cctx.Printer.Println("You already have a Temporal Cloud account. Run `temporal cloud login` to sign in.") + case onboarding.IsComplete(resp): + cctx.Printer.Printlnf("Your Temporal Cloud account is ready (%s). Run `temporal cloud login` to sign in.", + resp.GetState().GetUserEmail()) + default: + cctx.Printer.Printlnf("Email: %s", resp.GetState().GetUserEmail()) + cctx.Printer.Printlnf("Onboarding step: %s", resp.GetState().GetCurrentStep()) + } + return nil +} + +// loginMethods are the --login-method values, in picker order. +var loginMethods = []struct { + value string + label string +}{ + {value: "google", label: "Google"}, + {value: "microsoft", label: "Microsoft"}, + {value: "password", label: "Email + Password"}, +} + +// chooseLoginMethod returns --login-method if set. Otherwise, in an interactive +// terminal, it asks with an arrow-key menu. In any other case (scripts, agents, +// JSON output) it returns "" and Auth0 shows its own provider picker. +func (c *CloudSignupCommand) chooseLoginMethod(cctx *CommandContext) (string, error) { + if c.LoginMethod.Value != "" { + return c.LoginMethod.Value, nil + } + if cctx.JSONOutput || !cliprompter.IsTerminal() { + // Stderr, so JSON on stdout stays parseable and agents still see the hint. + fmt.Fprintln(cctx.Options.Stderr, + "No --login-method set: choose one in the browser, or pass --login-method google|microsoft|password.") + return "", nil + } + labels := make([]string, len(loginMethods)) + for i, conn := range loginMethods { + labels[i] = conn.label + } + i, err := cliprompter.SelectInTerminal("Sign up with:", labels) + if err != nil { + return "", err + } + return loginMethods[i].value, nil +} + +// connectionAuthParams maps a connection value to Auth0 authorize parameters, +// the same way the get-cloud website's sign-up buttons do. For "", Auth0 shows +// its own provider picker. +func (c *CloudSignupCommand) connectionAuthParams(connection string) []oauth2.AuthCodeOption { + switch connection { + case "google": + return []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("connection", "google-oauth2")} + case "microsoft": + // AIDEV-NOTE: the Microsoft connection is named differently per tenant + // (microsoft-v2 in prod, microsoft elsewhere), mirroring the website. + name := "microsoft" + if c.Domain == "login.tmprl.cloud" { + name = "microsoft-v2" + } + return []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("connection", name)} + case "password": + return []oauth2.AuthCodeOption{ + oauth2.SetAuthURLParam("connection", "Username-Password-Authentication"), + oauth2.SetAuthURLParam("screen_hint", "signup"), + } + default: + return nil + } +} + +func (c *CloudSignupCommand) dialOnboarding(tokenSource oauth2.TokenSource) (*grpc.ClientConn, error) { + transport := credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12}) + if c.OnboardingInsecure { + transport = insecure.NewCredentials() + } + conn, err := grpc.NewClient( + c.OnboardingAddress, + grpc.WithTransportCredentials(transport), + grpc.WithPerRPCCredentials(bearerTokenCredentials{ + tokenSource: tokenSource, + requireSecure: !c.OnboardingInsecure, + }), + ) + if err != nil { + return nil, fmt.Errorf("failed to connect to onboarding service: %w", err) + } + return conn, nil +} + +// bearerTokenCredentials attaches an OAuth access token to each RPC. Unlike +// grpc/credentials/oauth.TokenSource, it can be used without TLS so the +// command can reach a local onboarding service. +type bearerTokenCredentials struct { + tokenSource oauth2.TokenSource + requireSecure bool +} + +func (b bearerTokenCredentials) GetRequestMetadata(context.Context, ...string) (map[string]string, error) { + token, err := b.tokenSource.Token() + if err != nil { + return nil, fmt.Errorf("failed to get access token: %w", err) + } + return map[string]string{"authorization": "Bearer " + token.AccessToken}, nil +} + +func (b bearerTokenCredentials) RequireTransportSecurity() bool { + return b.requireSecure +} diff --git a/temporalcloudcli/commands.yml b/temporalcloudcli/commands.yml index 63e821b..d4f31fb 100644 --- a/temporalcloudcli/commands.yml +++ b/temporalcloudcli/commands.yml @@ -137,6 +137,75 @@ commands: Authentication domain for the OAuth provider. default: login.tmprl.cloud + - name: cloud signup + summary: Sign up for Temporal Cloud (prototype) + description: | + Sign up for Temporal Cloud from the terminal. + + This command opens your default browser to authenticate, then starts or + resumes your Temporal Cloud onboarding. The sign-up credential is kept in + memory only and is not written to your profile. + + Example: + + ``` + temporal cloud signup + ``` + has-init: true + docs: + keywords: + - signup + - onboarding + description-header: Sign up + tags: + - login + options: + - name: domain + type: string + hidden: true + description: | + Authentication domain for the OAuth provider. + default: login.tmprl.cloud + - name: audience + type: string + hidden: true + default: https://onboarding.tmprl.cloud + description: | + OAuth audience parameter for the sign-up token. + - name: login-method + type: string-enum + enum-values: [google, microsoft, password] + description: | + Login method to use, instead of choosing one interactively. + - name: client-id + type: string + hidden: true + default: Cd2erICRRO9hzuGeoQyqO9iPfiCgCvMZ + description: | + OAuth client identifier for authentication. + - name: redirect-url + type: string + hidden: true + default: http://127.0.0.1:56628/callback + description: | + Redirect URL for OAuth authentication flow. + - name: onboarding-address + type: string + hidden: true + default: onboarding.tmprl.cloud:443 + description: | + host:port of the Temporal Cloud onboarding service. + - name: onboarding-insecure + type: bool + hidden: true + description: | + Connect to the onboarding service without TLS. For local development only. + - name: no-wait + type: bool + hidden: true + description: | + Return the current onboarding state without waiting. Prototype only. + # Namespace commands - name: cloud namespace summary: Manage Temporal Cloud namespaces diff --git a/temporalcloudcli/oauth.go b/temporalcloudcli/oauth.go index f3b3b6a..db8be11 100644 --- a/temporalcloudcli/oauth.go +++ b/temporalcloudcli/oauth.go @@ -8,6 +8,7 @@ import ( "fmt" "net/http" "net/url" + "os" "sync" "time" @@ -20,7 +21,9 @@ type oauthCallbackResult struct { err error } -func Login(ctx context.Context, config *oauth2.Config, options ...oauth2.AuthCodeOption) (*oauth2.Token, error) { +// Login runs the browser-based authorization-code (PKCE) flow. When +// openBrowser is false, it only prints the URL for the user to open. +func Login(ctx context.Context, config *oauth2.Config, openBrowser bool, options ...oauth2.AuthCodeOption) (*oauth2.Token, error) { // Generate PKCE challenge. verifier := oauth2.GenerateVerifier() options = append(options, oauth2.S256ChallengeOption(verifier)) @@ -33,8 +36,15 @@ func Login(ctx context.Context, config *oauth2.Config, options ...oauth2.AuthCod state := base64.RawURLEncoding.EncodeToString(stateBytes[:]) authURL := config.AuthCodeURL(state, options...) - fmt.Printf("Opening browser to authorize. If it doesn't open, visit: %s\n", authURL) - _ = browser.OpenURL(authURL) + // Prompts go to stderr so stdout carries only command output (e.g. -o json). + if openBrowser { + fmt.Fprintf(os.Stderr, "Opening browser to authorize. If it doesn't open, visit: %s\n", authURL) + // The browser launcher's own output would also land on stdout by default. + browser.Stdout = os.Stderr + _ = browser.OpenURL(authURL) + } else { + fmt.Fprintf(os.Stderr, "Open this URL in a browser to authorize: %s\n", authURL) + } // Parse redirect URL to get host and path url, err := url.Parse(config.RedirectURL) diff --git a/temporalcloudcli/prompter/select.go b/temporalcloudcli/prompter/select.go new file mode 100644 index 0000000..2d5776a --- /dev/null +++ b/temporalcloudcli/prompter/select.go @@ -0,0 +1,145 @@ +package prompter + +import ( + "bufio" + "errors" + "fmt" + "io" + "os" + + "golang.org/x/term" +) + +// ErrSelectCanceled is returned when the user cancels a selection (Ctrl-C, +// Ctrl-D or q). +var ErrSelectCanceled = errors.New("selection canceled") + +const ( + keyCtrlC = 3 + keyCtrlD = 4 + keyEsc = 27 +) + +// IsTerminal reports whether stdin and stdout are both interactive terminals, +// so an arrow-key prompt can be shown. +func IsTerminal() bool { + return term.IsTerminal(int(os.Stdin.Fd())) && term.IsTerminal(int(os.Stdout.Fd())) +} + +// SelectInTerminal shows an arrow-key menu on stdout and returns the index of +// the chosen option. The caller must check IsTerminal first. +func SelectInTerminal(message string, options []string) (int, error) { + fd := int(os.Stdin.Fd()) + oldState, err := term.MakeRaw(fd) + if err != nil { + return 0, fmt.Errorf("failed to read from terminal: %w", err) + } + defer func() { _ = term.Restore(fd, oldState) }() + + return Select(os.Stdin, os.Stdout, message, options) +} + +// Select runs an arrow-key menu over in and out, which must already be in raw +// mode. Up/Down (or k/j) move, Enter chooses, and Ctrl-C, Ctrl-D or q cancel. +// It returns the index of the chosen option. +func Select(in io.Reader, out io.Writer, message string, options []string) (int, error) { + if len(options) == 0 { + return 0, errors.New("no options to select from") + } + + r := bufio.NewReader(in) + selected := 0 + + // Raw mode disables output post-processing, so lines end in \r\n. + fmt.Fprintf(out, "\x1b[?25l%s\r\n", message) + defer fmt.Fprint(out, "\x1b[?25h") + drawOptions(out, options, selected) + + for { + key, err := readKey(r) + if err != nil { + return 0, err + } + switch key { + case keyUp: + selected = (selected - 1 + len(options)) % len(options) + case keyDown: + selected = (selected + 1) % len(options) + case keyEnter: + clearOptions(out, len(options)) + fmt.Fprintf(out, "\x1b[1A\x1b[2K%s %s\r\n", message, options[selected]) + return selected, nil + case keyCancel: + clearOptions(out, len(options)) + return 0, ErrSelectCanceled + default: + continue + } + clearOptions(out, len(options)) + drawOptions(out, options, selected) + } +} + +type key int + +const ( + keyOther key = iota + keyUp + keyDown + keyEnter + keyCancel +) + +func readKey(r *bufio.Reader) (key, error) { + b, err := r.ReadByte() + if errors.Is(err, io.EOF) { + return keyCancel, nil + } + if err != nil { + return keyOther, fmt.Errorf("failed to read from terminal: %w", err) + } + switch b { + case '\r', '\n': + return keyEnter, nil + case keyCtrlC, keyCtrlD, 'q': + return keyCancel, nil + case 'k': + return keyUp, nil + case 'j': + return keyDown, nil + case keyEsc: + // Arrow keys arrive as ESC [ A/B, or ESC O A/B in application cursor mode. + prefix, err := r.ReadByte() + if err != nil || (prefix != '[' && prefix != 'O') { + return keyOther, nil + } + code, err := r.ReadByte() + if err != nil { + return keyOther, nil + } + switch code { + case 'A': + return keyUp, nil + case 'B': + return keyDown, nil + } + } + return keyOther, nil +} + +func drawOptions(out io.Writer, options []string, selected int) { + for i, opt := range options { + marker := " " + if i == selected { + marker = "> " + } + fmt.Fprintf(out, "%s%s\r\n", marker, opt) + } +} + +// clearOptions moves the cursor back over the drawn options and erases them. +func clearOptions(out io.Writer, n int) { + for range n { + fmt.Fprint(out, "\x1b[1A\x1b[2K") + } +} diff --git a/temporalcloudcli/prompter/select_test.go b/temporalcloudcli/prompter/select_test.go new file mode 100644 index 0000000..b68c547 --- /dev/null +++ b/temporalcloudcli/prompter/select_test.go @@ -0,0 +1,57 @@ +package prompter_test + +import ( + "bytes" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/temporalio/cloud-cli/temporalcloudcli/prompter" +) + +func TestSelect(t *testing.T) { + options := []string{"Google", "Microsoft", "Email + Password"} + + tests := []struct { + name string + input string + expectedIndex int + expectedErr error + }{ + {name: "enter picks the first option", input: "\r", expectedIndex: 0}, + {name: "down arrow", input: "\x1b[B\r", expectedIndex: 1}, + {name: "application mode down arrow", input: "\x1bOB\r", expectedIndex: 1}, + {name: "down twice", input: "\x1b[B\x1b[B\r", expectedIndex: 2}, + {name: "down wraps to the top", input: "\x1b[B\x1b[B\x1b[B\r", expectedIndex: 0}, + {name: "up wraps to the bottom", input: "\x1b[A\r", expectedIndex: 2}, + {name: "j and k", input: "jjk\r", expectedIndex: 1}, + {name: "other keys are ignored", input: "x\x1b[C\n", expectedIndex: 0}, + {name: "ctrl-c cancels", input: "\x1b[B\x03", expectedErr: prompter.ErrSelectCanceled}, + {name: "q cancels", input: "q", expectedErr: prompter.ErrSelectCanceled}, + {name: "eof cancels", input: "\x1b[B", expectedErr: prompter.ErrSelectCanceled}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var out bytes.Buffer + + index, err := prompter.Select(strings.NewReader(tt.input), &out, "Sign up with:", options) + + if tt.expectedErr != nil { + require.ErrorIs(t, err, tt.expectedErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.expectedIndex, index) + assert.Contains(t, out.String(), "Sign up with: "+options[tt.expectedIndex]) + }) + } +} + +func TestSelect_NoOptions(t *testing.T) { + _, err := prompter.Select(strings.NewReader("\r"), &bytes.Buffer{}, "Pick:", nil) + + require.EqualError(t, err, "no options to select from") +} From 6da780dcdedc70f34764d3a447593694c652002e Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Mon, 23 Nov 2026 23:38:14 -0500 Subject: [PATCH 03/15] Add unit tests --- temporalcloudcli/commands.signup_test.go | 57 ++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 temporalcloudcli/commands.signup_test.go diff --git a/temporalcloudcli/commands.signup_test.go b/temporalcloudcli/commands.signup_test.go new file mode 100644 index 0000000..737908a --- /dev/null +++ b/temporalcloudcli/commands.signup_test.go @@ -0,0 +1,57 @@ +package temporalcloudcli + +import ( + "net/url" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/oauth2" +) + +func TestConnectionAuthParams(t *testing.T) { + tests := []struct { + name string + domain string + method string + wantConnection string + wantScreenHint string + }{ + {name: "google", domain: "login.tmprl.cloud", method: "google", wantConnection: "google-oauth2"}, + {name: "microsoft prod", domain: "login.tmprl.cloud", method: "microsoft", wantConnection: "microsoft-v2"}, + {name: "microsoft non-prod", domain: "login.tmprl-test.cloud", method: "microsoft", wantConnection: "microsoft"}, + { + name: "password", + domain: "login.tmprl.cloud", + method: "password", + wantConnection: "Username-Password-Authentication", + wantScreenHint: "signup", + }, + {name: "unset leaves the choice to Auth0", domain: "login.tmprl.cloud", method: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := &CloudSignupCommand{Domain: tt.domain} + query := authorizeQuery(t, c.connectionAuthParams(tt.method)) + assert.Equal(t, tt.wantConnection, query.Get("connection")) + assert.Equal(t, tt.wantScreenHint, query.Get("screen_hint")) + }) + } +} + +// Guards against adding a picker entry without a matching Auth0 connection. +func TestLoginMethodsHaveConnections(t *testing.T) { + c := &CloudSignupCommand{Domain: "login.tmprl.cloud"} + for _, m := range loginMethods { + query := authorizeQuery(t, c.connectionAuthParams(m.value)) + assert.NotEmpty(t, query.Get("connection"), "login method %q has no connection", m.value) + } +} + +func authorizeQuery(t *testing.T, opts []oauth2.AuthCodeOption) url.Values { + t.Helper() + cfg := &oauth2.Config{Endpoint: oauth2.Endpoint{AuthURL: "https://example.com/authorize"}} + u, err := url.Parse(cfg.AuthCodeURL("state", opts...)) + require.NoError(t, err) + return u.Query() +} From 73246297c0f92a74eb1a133fb6c8aa2c26e83c01 Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Mon, 23 Nov 2026 23:43:23 -0500 Subject: [PATCH 04/15] Fix IsTerminal() --- temporalcloudcli/commands.signup.go | 4 +-- temporalcloudcli/prompter/select.go | 36 +++++++++++++++++------- temporalcloudcli/prompter/select_test.go | 9 ++++++ 3 files changed, 37 insertions(+), 12 deletions(-) diff --git a/temporalcloudcli/commands.signup.go b/temporalcloudcli/commands.signup.go index fe76712..7651ffa 100644 --- a/temporalcloudcli/commands.signup.go +++ b/temporalcloudcli/commands.signup.go @@ -102,7 +102,7 @@ func (c *CloudSignupCommand) chooseLoginMethod(cctx *CommandContext) (string, er if c.LoginMethod.Value != "" { return c.LoginMethod.Value, nil } - if cctx.JSONOutput || !cliprompter.IsTerminal() { + if cctx.JSONOutput || !cliprompter.IsTerminal(cctx.Options.Stdin, cctx.Options.Stdout) { // Stderr, so JSON on stdout stays parseable and agents still see the hint. fmt.Fprintln(cctx.Options.Stderr, "No --login-method set: choose one in the browser, or pass --login-method google|microsoft|password.") @@ -112,7 +112,7 @@ func (c *CloudSignupCommand) chooseLoginMethod(cctx *CommandContext) (string, er for i, conn := range loginMethods { labels[i] = conn.label } - i, err := cliprompter.SelectInTerminal("Sign up with:", labels) + i, err := cliprompter.SelectInTerminal(cctx.Options.Stdin, cctx.Options.Stdout, "Sign up with:", labels) if err != nil { return "", err } diff --git a/temporalcloudcli/prompter/select.go b/temporalcloudcli/prompter/select.go index 2d5776a..f946227 100644 --- a/temporalcloudcli/prompter/select.go +++ b/temporalcloudcli/prompter/select.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io" - "os" "golang.org/x/term" ) @@ -20,23 +19,40 @@ const ( keyEsc = 27 ) -// IsTerminal reports whether stdin and stdout are both interactive terminals, -// so an arrow-key prompt can be shown. -func IsTerminal() bool { - return term.IsTerminal(int(os.Stdin.Fd())) && term.IsTerminal(int(os.Stdout.Fd())) +// fdFile is satisfied by *os.File, the only kind of stream that can be a +// terminal. +type fdFile interface { + Fd() uintptr } -// SelectInTerminal shows an arrow-key menu on stdout and returns the index of -// the chosen option. The caller must check IsTerminal first. -func SelectInTerminal(message string, options []string) (int, error) { - fd := int(os.Stdin.Fd()) +// IsTerminal reports whether in and out are both interactive terminals, so an +// arrow-key prompt can be shown. Streams that aren't files, such as buffers in +// tests, are never terminals. +func IsTerminal(in io.Reader, out io.Writer) bool { + return isTerminal(in) && isTerminal(out) +} + +func isTerminal(stream any) bool { + f, ok := stream.(fdFile) + return ok && term.IsTerminal(int(f.Fd())) +} + +// SelectInTerminal puts in into raw mode, shows an arrow-key menu on out and +// returns the index of the chosen option. The caller must check IsTerminal +// first. +func SelectInTerminal(in io.Reader, out io.Writer, message string, options []string) (int, error) { + f, ok := in.(fdFile) + if !ok { + return 0, errors.New("input is not a terminal") + } + fd := int(f.Fd()) oldState, err := term.MakeRaw(fd) if err != nil { return 0, fmt.Errorf("failed to read from terminal: %w", err) } defer func() { _ = term.Restore(fd, oldState) }() - return Select(os.Stdin, os.Stdout, message, options) + return Select(in, out, message, options) } // Select runs an arrow-key menu over in and out, which must already be in raw diff --git a/temporalcloudcli/prompter/select_test.go b/temporalcloudcli/prompter/select_test.go index b68c547..1e7d4cf 100644 --- a/temporalcloudcli/prompter/select_test.go +++ b/temporalcloudcli/prompter/select_test.go @@ -55,3 +55,12 @@ func TestSelect_NoOptions(t *testing.T) { require.EqualError(t, err, "no options to select from") } + +func TestIsTerminal_NonFileStreams(t *testing.T) { + assert.False(t, prompter.IsTerminal(strings.NewReader(""), &bytes.Buffer{})) +} + +func TestSelectInTerminal_NonFileInput(t *testing.T) { + _, err := prompter.SelectInTerminal(strings.NewReader(""), &bytes.Buffer{}, "Pick:", []string{"a"}) + require.Error(t, err) +} From 9d9abbbfe793ea79c6723a9d568b6e82fc6ef61f Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Mon, 23 Nov 2026 23:56:23 -0500 Subject: [PATCH 05/15] Cosmetic changes --- internal/onboarding/wait.go | 19 +++---------------- proto/onboardingservice/v1/service.proto | 3 +-- temporalcloudcli/oauth.go | 1 - temporalcloudcli/prompter/select.go | 15 ++++++--------- 4 files changed, 10 insertions(+), 28 deletions(-) diff --git a/internal/onboarding/wait.go b/internal/onboarding/wait.go index bf0b0e7..c32d8cf 100644 --- a/internal/onboarding/wait.go +++ b/internal/onboarding/wait.go @@ -1,5 +1,3 @@ -// Package onboarding polls the Temporal Cloud onboarding service until a -// CLI-started sign-up is complete. package onboarding import ( @@ -15,7 +13,6 @@ import ( onboardingservice "github.com/temporalio/cloud-cli/internal/onboardingservice/v1" ) -// Client is the subset of the onboarding service the CLI calls. type Client interface { GetOrCreateCLIOnboardingState( ctx context.Context, @@ -24,33 +21,26 @@ type Client interface { ) (*onboardingservice.GetOrCreateCLIOnboardingStateResponse, error) } -// PollConfig controls the polling backoff. It mirrors the get-cloud website: -// a fixed interval for the first FastAttempts polls, then doubling up to -// MaxInterval. type PollConfig struct { Interval time.Duration MaxInterval time.Duration FastAttempts int } -// DefaultPollConfig matches the website's waitForStep: 1s for 10 polls, then -// doubling to a 30s cap. +// DefaultPollConfig matches the website's waitForStep: +// 1s for 10 polls, then doubling to a 30s cap. var DefaultPollConfig = PollConfig{ Interval: time.Second, MaxInterval: 30 * time.Second, FastAttempts: 10, } -// IsComplete reports whether sign-up has finished, either just now or earlier. func IsComplete(resp *onboardingservice.GetOrCreateCLIOnboardingStateResponse) bool { return resp.GetUserAlreadyExists() || resp.GetState().GetCurrentStep() == onboardingservice.StepType_STEP_TYPE_END_OF_FUNNEL } -// Wait calls GetOrCreateCLIOnboardingState until sign-up is complete, ctx is -// done, or the service returns an error that is not worth retrying. The first -// call creates the onboarding session; the rest observe it. onStep, if set, is -// called each time the reported step changes. +// Wait calls GetOrCreateCLIOnboardingState until onboarding is complete. func Wait( ctx context.Context, client Client, @@ -93,9 +83,6 @@ func Wait( } } -// isRetryable covers transient transport failures and the service's per-email -// rate limit. Anything else (auth, allow list, invalid idp) will not change on -// retry. func isRetryable(err error) bool { switch status.Code(err) { case codes.Unavailable, codes.ResourceExhausted: diff --git a/proto/onboardingservice/v1/service.proto b/proto/onboardingservice/v1/service.proto index 03e869b..727f383 100644 --- a/proto/onboardingservice/v1/service.proto +++ b/proto/onboardingservice/v1/service.proto @@ -3,8 +3,7 @@ syntax = "proto3"; // Vendored subset of saas-proto proto/onboardingservice/v1/service.proto. // saas-proto is the source of truth. Keep the package, service, RPC and message // names identical to it: they form the gRPC method path on the wire. Only the -// RPCs the CLI calls are copied here. Changes must be additive and land in -// saas-proto first. +// RPCs the CLI calls are copied here. package onboardingservice.v1; option go_package = "github.com/temporalio/cloud-cli/internal/onboardingservice/v1;onboardingservice"; diff --git a/temporalcloudcli/oauth.go b/temporalcloudcli/oauth.go index db8be11..5f2a475 100644 --- a/temporalcloudcli/oauth.go +++ b/temporalcloudcli/oauth.go @@ -39,7 +39,6 @@ func Login(ctx context.Context, config *oauth2.Config, openBrowser bool, options // Prompts go to stderr so stdout carries only command output (e.g. -o json). if openBrowser { fmt.Fprintf(os.Stderr, "Opening browser to authorize. If it doesn't open, visit: %s\n", authURL) - // The browser launcher's own output would also land on stdout by default. browser.Stdout = os.Stderr _ = browser.OpenURL(authURL) } else { diff --git a/temporalcloudcli/prompter/select.go b/temporalcloudcli/prompter/select.go index f946227..16977c6 100644 --- a/temporalcloudcli/prompter/select.go +++ b/temporalcloudcli/prompter/select.go @@ -9,25 +9,22 @@ import ( "golang.org/x/term" ) -// ErrSelectCanceled is returned when the user cancels a selection (Ctrl-C, -// Ctrl-D or q). +// ErrSelectCanceled is returned when the user cancels a selection (Ctrl-C, Ctrl-D or q). var ErrSelectCanceled = errors.New("selection canceled") const ( - keyCtrlC = 3 - keyCtrlD = 4 - keyEsc = 27 + keyCtrlC = '\x03' + keyCtrlD = '\x04' + keyEsc = '\x1b' ) -// fdFile is satisfied by *os.File, the only kind of stream that can be a -// terminal. +// fdFile is satisfied by *os.File, the only kind of stream that can be a terminal. type fdFile interface { Fd() uintptr } // IsTerminal reports whether in and out are both interactive terminals, so an -// arrow-key prompt can be shown. Streams that aren't files, such as buffers in -// tests, are never terminals. +// arrow-key prompt can be shown. func IsTerminal(in io.Reader, out io.Writer) bool { return isTerminal(in) && isTerminal(out) } From 1349eba398cde3b00da4dec35a70324058e92fa2 Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Tue, 24 Nov 2026 00:01:44 -0500 Subject: [PATCH 06/15] Clarify connection mapping logic --- temporalcloudcli/commands.signup.go | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/temporalcloudcli/commands.signup.go b/temporalcloudcli/commands.signup.go index 7651ffa..f48ee9c 100644 --- a/temporalcloudcli/commands.signup.go +++ b/temporalcloudcli/commands.signup.go @@ -16,16 +16,11 @@ import ( cliprompter "github.com/temporalio/cloud-cli/temporalcloudcli/prompter" ) -// initCommand hides the command from help while it is a prototype: the prod -// onboarding service does not serve this RPC yet. Remove before launch. +// initCommand hides the command from help while it is in development. func (c *CloudSignupCommand) initCommand(*CommandContext) { c.Command.Hidden = true } -// AIDEV-NOTE: Prototype. The sign-up token (aud=onboarding) is kept in memory -// only and never written to the profile: storing it in [oauth] would make every -// other command send an onboarding-audience token to saas-api. The saas-api -// login that ends sign-up is a separate step once onboarding is complete. func (c *CloudSignupCommand) run(cctx *CommandContext, _ []string) error { oauthConfig, err := newOAuthClientConfig(c.Domain, c.ClientId, c.RedirectUrl) if err != nil { @@ -57,8 +52,6 @@ func (c *CloudSignupCommand) run(cctx *CommandContext, _ []string) error { return fmt.Errorf("failed to get onboarding state: %w", err) } } else { - // Waits until provisioning finishes or the command is canceled; the global - // --command-timeout, when set, also bounds this. resp, err = onboarding.Wait(cctx, client, req, onboarding.DefaultPollConfig, func(step onboardingservice.StepType) { if !cctx.JSONOutput { cctx.Printer.Printlnf("Waiting for your account (step: %s)...", step) @@ -85,7 +78,6 @@ func (c *CloudSignupCommand) run(cctx *CommandContext, _ []string) error { return nil } -// loginMethods are the --login-method values, in picker order. var loginMethods = []struct { value string label string @@ -120,14 +112,13 @@ func (c *CloudSignupCommand) chooseLoginMethod(cctx *CommandContext) (string, er } // connectionAuthParams maps a connection value to Auth0 authorize parameters, -// the same way the get-cloud website's sign-up buttons do. For "", Auth0 shows -// its own provider picker. +// the same way the /get-cloud sign-up buttons do. func (c *CloudSignupCommand) connectionAuthParams(connection string) []oauth2.AuthCodeOption { switch connection { case "google": return []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("connection", "google-oauth2")} case "microsoft": - // AIDEV-NOTE: the Microsoft connection is named differently per tenant + // The Microsoft connection is named differently per tenant // (microsoft-v2 in prod, microsoft elsewhere), mirroring the website. name := "microsoft" if c.Domain == "login.tmprl.cloud" { From 9105bb2546b77b01ea6a8a578999be1f6718ee10 Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Tue, 24 Nov 2026 01:07:45 -0500 Subject: [PATCH 07/15] Clean up output on onboarding --- temporalcloudcli/commands.signup.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/temporalcloudcli/commands.signup.go b/temporalcloudcli/commands.signup.go index f48ee9c..9cf2e8c 100644 --- a/temporalcloudcli/commands.signup.go +++ b/temporalcloudcli/commands.signup.go @@ -69,10 +69,8 @@ func (c *CloudSignupCommand) run(cctx *CommandContext, _ []string) error { case resp.GetUserAlreadyExists(): cctx.Printer.Println("You already have a Temporal Cloud account. Run `temporal cloud login` to sign in.") case onboarding.IsComplete(resp): - cctx.Printer.Printlnf("Your Temporal Cloud account is ready (%s). Run `temporal cloud login` to sign in.", - resp.GetState().GetUserEmail()) + cctx.Printer.Println("Your Temporal Cloud account is ready. Run `temporal cloud login` to sign in.") default: - cctx.Printer.Printlnf("Email: %s", resp.GetState().GetUserEmail()) cctx.Printer.Printlnf("Onboarding step: %s", resp.GetState().GetCurrentStep()) } return nil From 7f5e008059764a7b127f40bb731a6ec484d45e59 Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Tue, 24 Nov 2026 17:54:10 -0500 Subject: [PATCH 08/15] Handle email+password --- temporalcloudcli/commands.signup.go | 47 ++++++++++++++++++- temporalcloudcli/commands.signup_test.go | 57 ------------------------ temporalcloudcli/oauth.go | 37 ++++++++++++--- 3 files changed, 78 insertions(+), 63 deletions(-) delete mode 100644 temporalcloudcli/commands.signup_test.go diff --git a/temporalcloudcli/commands.signup.go b/temporalcloudcli/commands.signup.go index 9cf2e8c..60d1433 100644 --- a/temporalcloudcli/commands.signup.go +++ b/temporalcloudcli/commands.signup.go @@ -1,9 +1,12 @@ package temporalcloudcli import ( + "bufio" "context" "crypto/tls" + "errors" "fmt" + "io" "golang.org/x/oauth2" "google.golang.org/grpc" @@ -32,7 +35,7 @@ func (c *CloudSignupCommand) run(cctx *CommandContext, _ []string) error { return err } authParams := append([]oauth2.AuthCodeOption{oauth2.SetAuthURLParam("audience", c.Audience)}, c.connectionAuthParams(connection)...) - token, err := Login(cctx, oauthConfig, !c.Parent.DisablePopUp, authParams...) + token, err := c.login(cctx, oauthConfig, authParams) if err != nil { return fmt.Errorf("failed to login: %w", err) } @@ -76,6 +79,48 @@ func (c *CloudSignupCommand) run(cctx *CommandContext, _ []string) error { return nil } +// login runs the browser login. A new email + password user is denied until +// they verify their email, so in a terminal it waits for them to click the +// emailed link and then logs in again, instead of making them rerun signup. +func (c *CloudSignupCommand) login(cctx *CommandContext, config *oauth2.Config, authParams []oauth2.AuthCodeOption) (*oauth2.Token, error) { + for { + token, err := Login(cctx, config, !c.Parent.DisablePopUp, authParams...) + var authErr *AuthorizationError + if !errors.As(err, &authErr) || !authErr.IsEmailNotVerified() { + return token, err + } + if !cliprompter.IsTerminal(cctx.Options.Stdin, cctx.Options.Stderr) { + return nil, errors.New("verify your email using the link we sent you, then run signup again") + } + fmt.Fprint(cctx.Options.Stderr, + "Verify your email using the link we sent you, then press Enter to continue.") + if err := waitForEnter(cctx, cctx.Options.Stdin); err != nil { + return nil, err + } + // The account now exists, so show the login form rather than sign-up. + authParams = append(authParams, oauth2.SetAuthURLParam("screen_hint", "login")) + } +} + +// waitForEnter blocks until a line is read from in or ctx is canceled. Ctrl-C +// cancels ctx rather than killing the process, so a plain read would hang. +func waitForEnter(ctx context.Context, in io.Reader) error { + done := make(chan error, 1) + go func() { + _, err := bufio.NewReader(in).ReadString('\n') + done <- err + }() + select { + case err := <-done: + if err != nil { + return fmt.Errorf("failed to read from terminal: %w", err) + } + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + var loginMethods = []struct { value string label string diff --git a/temporalcloudcli/commands.signup_test.go b/temporalcloudcli/commands.signup_test.go deleted file mode 100644 index 737908a..0000000 --- a/temporalcloudcli/commands.signup_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package temporalcloudcli - -import ( - "net/url" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "golang.org/x/oauth2" -) - -func TestConnectionAuthParams(t *testing.T) { - tests := []struct { - name string - domain string - method string - wantConnection string - wantScreenHint string - }{ - {name: "google", domain: "login.tmprl.cloud", method: "google", wantConnection: "google-oauth2"}, - {name: "microsoft prod", domain: "login.tmprl.cloud", method: "microsoft", wantConnection: "microsoft-v2"}, - {name: "microsoft non-prod", domain: "login.tmprl-test.cloud", method: "microsoft", wantConnection: "microsoft"}, - { - name: "password", - domain: "login.tmprl.cloud", - method: "password", - wantConnection: "Username-Password-Authentication", - wantScreenHint: "signup", - }, - {name: "unset leaves the choice to Auth0", domain: "login.tmprl.cloud", method: ""}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - c := &CloudSignupCommand{Domain: tt.domain} - query := authorizeQuery(t, c.connectionAuthParams(tt.method)) - assert.Equal(t, tt.wantConnection, query.Get("connection")) - assert.Equal(t, tt.wantScreenHint, query.Get("screen_hint")) - }) - } -} - -// Guards against adding a picker entry without a matching Auth0 connection. -func TestLoginMethodsHaveConnections(t *testing.T) { - c := &CloudSignupCommand{Domain: "login.tmprl.cloud"} - for _, m := range loginMethods { - query := authorizeQuery(t, c.connectionAuthParams(m.value)) - assert.NotEmpty(t, query.Get("connection"), "login method %q has no connection", m.value) - } -} - -func authorizeQuery(t *testing.T, opts []oauth2.AuthCodeOption) url.Values { - t.Helper() - cfg := &oauth2.Config{Endpoint: oauth2.Endpoint{AuthURL: "https://example.com/authorize"}} - u, err := url.Parse(cfg.AuthCodeURL("state", opts...)) - require.NoError(t, err) - return u.Query() -} diff --git a/temporalcloudcli/oauth.go b/temporalcloudcli/oauth.go index 5f2a475..d5934f4 100644 --- a/temporalcloudcli/oauth.go +++ b/temporalcloudcli/oauth.go @@ -70,12 +70,13 @@ func Login(ctx context.Context, config *oauth2.Config, openBrowser bool, options // Check for OAuth error response. if errCode := query.Get("error"); errCode != "" { - errDesc := query.Get("error_description") - if errDesc == "" { - errDesc = errCode + authErr := &AuthorizationError{Code: errCode, Description: query.Get("error_description")} + resultCh <- oauthCallbackResult{err: authErr} + if authErr.IsEmailNotVerified() { + http.Error(w, "Check your email for a verification link, then return to your terminal.", http.StatusForbidden) + return } - resultCh <- oauthCallbackResult{err: fmt.Errorf("authorization failed: %s", errDesc)} - http.Error(w, fmt.Sprintf("Authorization failed: %s", errDesc), http.StatusBadRequest) + http.Error(w, "Authorization failed: "+authErr.reason(), http.StatusBadRequest) return } @@ -133,6 +134,32 @@ func Login(ctx context.Context, config *oauth2.Config, openBrowser bool, options return token, nil } +// AuthorizationError is an OAuth error returned to the callback, such as a +// login denied by an Auth0 action. +type AuthorizationError struct { + Code string + Description string +} + +func (e *AuthorizationError) Error() string { + return "authorization failed: " + e.reason() +} + +func (e *AuthorizationError) reason() string { + if e.Description != "" { + return e.Description + } + return e.Code +} + +// IsEmailNotVerified reports whether the login was denied because the user's +// email address is not verified yet. +// AIDEV-NOTE: the post-login email-verify action denies password logins with +// api.access.deny('verify_email'); the website checks for the same value. +func (e *AuthorizationError) IsEmailNotVerified() bool { + return e.Code == "access_denied" && e.Description == "verify_email" +} + var ErrLoginRequired = errors.New("login required") func GetToken(ctx context.Context, config *oauth2.Config, token *oauth2.Token) (*oauth2.Token, bool, error) { From a2b55fcbca399fb158d857ba7ee3dacc8654a897 Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Tue, 24 Nov 2026 18:18:13 -0500 Subject: [PATCH 09/15] Rerun on email_verify --- temporalcloudcli/commands.signup.go | 47 +++++------------------------ 1 file changed, 7 insertions(+), 40 deletions(-) diff --git a/temporalcloudcli/commands.signup.go b/temporalcloudcli/commands.signup.go index 60d1433..5487d88 100644 --- a/temporalcloudcli/commands.signup.go +++ b/temporalcloudcli/commands.signup.go @@ -1,12 +1,10 @@ package temporalcloudcli import ( - "bufio" "context" "crypto/tls" "errors" "fmt" - "io" "golang.org/x/oauth2" "google.golang.org/grpc" @@ -79,46 +77,15 @@ func (c *CloudSignupCommand) run(cctx *CommandContext, _ []string) error { return nil } -// login runs the browser login. A new email + password user is denied until -// they verify their email, so in a terminal it waits for them to click the -// emailed link and then logs in again, instead of making them rerun signup. +// login runs the browser login. Auth0 denies a new email + password user until +// they verify their email; signup is safe to rerun, so it asks them to do that. func (c *CloudSignupCommand) login(cctx *CommandContext, config *oauth2.Config, authParams []oauth2.AuthCodeOption) (*oauth2.Token, error) { - for { - token, err := Login(cctx, config, !c.Parent.DisablePopUp, authParams...) - var authErr *AuthorizationError - if !errors.As(err, &authErr) || !authErr.IsEmailNotVerified() { - return token, err - } - if !cliprompter.IsTerminal(cctx.Options.Stdin, cctx.Options.Stderr) { - return nil, errors.New("verify your email using the link we sent you, then run signup again") - } - fmt.Fprint(cctx.Options.Stderr, - "Verify your email using the link we sent you, then press Enter to continue.") - if err := waitForEnter(cctx, cctx.Options.Stdin); err != nil { - return nil, err - } - // The account now exists, so show the login form rather than sign-up. - authParams = append(authParams, oauth2.SetAuthURLParam("screen_hint", "login")) - } -} - -// waitForEnter blocks until a line is read from in or ctx is canceled. Ctrl-C -// cancels ctx rather than killing the process, so a plain read would hang. -func waitForEnter(ctx context.Context, in io.Reader) error { - done := make(chan error, 1) - go func() { - _, err := bufio.NewReader(in).ReadString('\n') - done <- err - }() - select { - case err := <-done: - if err != nil { - return fmt.Errorf("failed to read from terminal: %w", err) - } - return nil - case <-ctx.Done(): - return ctx.Err() + token, err := Login(cctx, config, !c.Parent.DisablePopUp, authParams...) + var authErr *AuthorizationError + if errors.As(err, &authErr) && authErr.IsEmailNotVerified() { + return nil, errors.New("verify your email using the link we sent you, then run `temporal cloud signup` again") } + return token, err } var loginMethods = []struct { From d4f0c6802d8877ceca860c209bf0ff0e96909291 Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Wed, 25 Nov 2026 00:21:34 -0500 Subject: [PATCH 10/15] Cap failures on Wait --- internal/onboarding/wait.go | 22 ++++++++++++++++++---- internal/onboarding/wait_test.go | 27 ++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/internal/onboarding/wait.go b/internal/onboarding/wait.go index c32d8cf..0830548 100644 --- a/internal/onboarding/wait.go +++ b/internal/onboarding/wait.go @@ -25,14 +25,21 @@ type PollConfig struct { Interval time.Duration MaxInterval time.Duration FastAttempts int + // MaxConsecutiveFailures is how many retryable errors in a row Wait + // tolerates before returning the last one. A successful response resets + // the count. Zero means no limit. + MaxConsecutiveFailures int } // DefaultPollConfig matches the website's waitForStep: -// 1s for 10 polls, then doubling to a 30s cap. +// 1s for 10 polls, then doubling to a 30s cap. 15 failures in a row gives up +// after about 40s if the first polls fail, or about 7.5 minutes once polling +// has slowed to 30s. var DefaultPollConfig = PollConfig{ - Interval: time.Second, - MaxInterval: 30 * time.Second, - FastAttempts: 10, + Interval: time.Second, + MaxInterval: 30 * time.Second, + FastAttempts: 10, + MaxConsecutiveFailures: 15, } func IsComplete(resp *onboardingservice.GetOrCreateCLIOnboardingStateResponse) bool { @@ -50,6 +57,7 @@ func Wait( ) (*onboardingservice.GetOrCreateCLIOnboardingStateResponse, error) { interval := cfg.Interval lastStep := onboardingservice.StepType(-1) + failures := 0 for attempt := 1; ; attempt++ { resp, err := client.GetOrCreateCLIOnboardingState(ctx, req) @@ -57,6 +65,7 @@ func Wait( case ctx.Err() != nil: return nil, waitError(ctx, lastStep) case err == nil: + failures = 0 if IsComplete(resp) { return resp, nil } @@ -68,6 +77,11 @@ func Wait( } case !isRetryable(err): return nil, fmt.Errorf("failed to get onboarding state: %w", err) + default: + failures++ + if cfg.MaxConsecutiveFailures > 0 && failures >= cfg.MaxConsecutiveFailures { + return nil, fmt.Errorf("failed to get onboarding state: %w", err) + } } if attempt > cfg.FastAttempts { diff --git a/internal/onboarding/wait_test.go b/internal/onboarding/wait_test.go index b7ba8bd..5304f6b 100644 --- a/internal/onboarding/wait_test.go +++ b/internal/onboarding/wait_test.go @@ -56,6 +56,7 @@ func TestWait(t *testing.T) { expectedErr string expectedCalls int expectedSteps []onboardingservice.StepType + maxFailures int }{ { name: "user already exists returns immediately", @@ -93,6 +94,28 @@ func TestWait(t *testing.T) { expectedErr: "timed out waiting for onboarding to complete (last step: STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION)", expectedSteps: []onboardingservice.StepType{onboardingservice.StepType_STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION}, }, + { + name: "gives up after too many failures in a row", + results: []result{{err: status.Error(codes.Unavailable, "down")}}, + maxFailures: 3, + expectedErr: "failed to get onboarding state: rpc error: code = Unavailable desc = down", + expectedCalls: 3, + }, + { + name: "a successful response resets the failure count", + results: []result{ + {err: status.Error(codes.Unavailable, "down")}, + {err: status.Error(codes.Unavailable, "down")}, + creating, + {err: status.Error(codes.Unavailable, "down")}, + {err: status.Error(codes.Unavailable, "down")}, + done, + }, + maxFailures: 3, + expectedResp: done.resp, + expectedCalls: 6, + expectedSteps: []onboardingservice.StepType{onboardingservice.StepType_STEP_TYPE_WAIT_FOR_ACCOUNT_CREATION}, + }, { name: "times out before any state", results: []result{{err: status.Error(codes.Unavailable, "down")}}, @@ -112,7 +135,9 @@ func TestWait(t *testing.T) { client := &fakeClient{results: tt.results} var steps []onboardingservice.StepType - resp, err := onboarding.Wait(ctx, client, &onboardingservice.GetOrCreateCLIOnboardingStateRequest{}, fastPoll, + cfg := fastPoll + cfg.MaxConsecutiveFailures = tt.maxFailures + resp, err := onboarding.Wait(ctx, client, &onboardingservice.GetOrCreateCLIOnboardingStateRequest{}, cfg, func(s onboardingservice.StepType) { steps = append(steps, s) }) if tt.expectedErr != "" { From 6ba4ce11f760816203156974b3439338adabb720 Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Wed, 25 Nov 2026 00:35:48 -0500 Subject: [PATCH 11/15] Clean up proto --- buf.yaml | 1 - .../onboardingservice/v1/onboarding.pb.go | 18 ++++++------- internal/onboardingservice/v1/service.pb.go | 8 +++--- .../onboardingservice/v1/service_grpc.pb.go | 16 +++++------- proto/onboardingservice/v1/onboarding.proto | 26 +++---------------- proto/onboardingservice/v1/service.proto | 11 ++++---- 6 files changed, 27 insertions(+), 53 deletions(-) diff --git a/buf.yaml b/buf.yaml index 1c5534a..edddcf7 100644 --- a/buf.yaml +++ b/buf.yaml @@ -5,7 +5,6 @@ lint: use: - STANDARD except: - # Names and layout mirror saas-proto, which is the source of truth. - PACKAGE_DIRECTORY_MATCH - RPC_REQUEST_RESPONSE_UNIQUE - RPC_REQUEST_STANDARD_NAME diff --git a/internal/onboardingservice/v1/onboarding.pb.go b/internal/onboardingservice/v1/onboarding.pb.go index e3f29fa..88f4151 100644 --- a/internal/onboardingservice/v1/onboarding.pb.go +++ b/internal/onboardingservice/v1/onboarding.pb.go @@ -4,11 +4,9 @@ // protoc (unknown) // source: onboardingservice/v1/onboarding.proto -// Vendored subset of saas-proto proto/onboardingservice/v1/onboarding.proto. -// saas-proto is the source of truth. Field names, numbers and types must match -// it exactly. Fields the CLI does not need, and that would pull in private -// saas-proto imports, are left out and reserved here; the decoder skips them as -// unknown fields. Changes must be additive and land in saas-proto first. +// The subset of the Temporal Cloud onboarding messages that the CLI uses. Field +// numbers and types must match the server exactly. Fields the CLI doesn't use +// are reserved, and the decoder skips them as unknown fields. package onboardingservice @@ -254,7 +252,7 @@ type CustomerDetails struct { FirstName string `protobuf:"bytes,1,opt,name=first_name,json=firstName,proto3" json:"first_name,omitempty"` // The last name of the customer. LastName string `protobuf:"bytes,2,opt,name=last_name,json=lastName,proto3" json:"last_name,omitempty"` - // The name of the company the user is from. If empty, the server defaults to "Personal". + // The name of the company the user is from. CompanyName string `protobuf:"bytes,3,opt,name=company_name,json=companyName,proto3" json:"company_name,omitempty"` // The country of the user. Country string `protobuf:"bytes,4,opt,name=country,proto3" json:"country,omitempty"` @@ -333,24 +331,24 @@ var File_onboardingservice_v1_onboarding_proto protoreflect.FileDescriptor const file_onboardingservice_v1_onboarding_proto_rawDesc = "" + "\n" + - "%onboardingservice/v1/onboarding.proto\x12\x14onboardingservice.v1\"\xeb\x02\n" + + "%onboardingservice/v1/onboarding.proto\x12\x14onboardingservice.v1\"\x98\x01\n" + "\x0fOnboardingState\x12A\n" + "\fcurrent_step\x18\x01 \x01(\x0e2\x1e.onboardingservice.v1.StepTypeR\vcurrentStep\x12\x1d\n" + "\n" + "user_email\x18\a \x01(\tR\tuserEmail\x12\x17\n" + - "\auser_id\x18\f \x01(\tR\x06userIdJ\x04\b\x02\x10\aJ\x04\b\b\x10\fR\x1bcustomer_details_collectionR\x11wait_for_throttleR\fstripe_setupR stripe_setup_intent_confirmationR\x19wait_for_account_creationR\x13eligible_promotionsR\x16eligible_billing_plansR\x0ftarget_sku_typeR\x18billing_provider_details\"x\n" + + "\auser_id\x18\f \x01(\tR\x06userIdJ\x04\b\x02\x10\aJ\x04\b\b\x10\f\"x\n" + "$GetOrCreateCLIOnboardingStateRequest\x12P\n" + "\x10customer_details\x18\x01 \x01(\v2%.onboardingservice.v1.CustomerDetailsR\x0fcustomerDetails\"\x94\x01\n" + "%GetOrCreateCLIOnboardingStateResponse\x12.\n" + "\x13user_already_exists\x18\x01 \x01(\bR\x11userAlreadyExists\x12;\n" + - "\x05state\x18\x02 \x01(\v2%.onboardingservice.v1.OnboardingStateR\x05state\"\xf2\x01\n" + + "\x05state\x18\x02 \x01(\v2%.onboardingservice.v1.OnboardingStateR\x05state\"\xd1\x01\n" + "\x0fCustomerDetails\x12\x1d\n" + "\n" + "first_name\x18\x01 \x01(\tR\tfirstName\x12\x1b\n" + "\tlast_name\x18\x02 \x01(\tR\blastName\x12!\n" + "\fcompany_name\x18\x03 \x01(\tR\vcompanyName\x12\x18\n" + "\acountry\x18\x04 \x01(\tR\acountry\x123\n" + - "\x16opt_in_marketing_email\x18\a \x01(\bR\x13optInMarketingEmailJ\x04\b\x05\x10\x06J\x04\b\x06\x10\aJ\x04\b\b\x10\tR\x16agree_terms_of_serviceR\apurpose*\x88\x02\n" + + "\x16opt_in_marketing_email\x18\a \x01(\bR\x13optInMarketingEmailJ\x04\b\x05\x10\x06J\x04\b\x06\x10\aJ\x04\b\b\x10\t*\x88\x02\n" + "\bStepType\x12\x19\n" + "\x15STEP_TYPE_UNSPECIFIED\x10\x00\x12)\n" + "%STEP_TYPE_CUSTOMER_DETAILS_COLLECTION\x10\x01\x12\x1f\n" + diff --git a/internal/onboardingservice/v1/service.pb.go b/internal/onboardingservice/v1/service.pb.go index 5df1eaa..4a9cab8 100644 --- a/internal/onboardingservice/v1/service.pb.go +++ b/internal/onboardingservice/v1/service.pb.go @@ -4,11 +4,9 @@ // protoc (unknown) // source: onboardingservice/v1/service.proto -// Vendored subset of saas-proto proto/onboardingservice/v1/service.proto. -// saas-proto is the source of truth. Keep the package, service, RPC and message -// names identical to it: they form the gRPC method path on the wire. Only the -// RPCs the CLI calls are copied here. Changes must be additive and land in -// saas-proto first. +// The subset of the Temporal Cloud onboarding service that the CLI calls. The +// package, service, RPC and message names form the gRPC method path on the +// wire, so they must match the server exactly. package onboardingservice diff --git a/internal/onboardingservice/v1/service_grpc.pb.go b/internal/onboardingservice/v1/service_grpc.pb.go index 8894c77..0a47aba 100644 --- a/internal/onboardingservice/v1/service_grpc.pb.go +++ b/internal/onboardingservice/v1/service_grpc.pb.go @@ -4,11 +4,9 @@ // - protoc (unknown) // source: onboardingservice/v1/service.proto -// Vendored subset of saas-proto proto/onboardingservice/v1/service.proto. -// saas-proto is the source of truth. Keep the package, service, RPC and message -// names identical to it: they form the gRPC method path on the wire. Only the -// RPCs the CLI calls are copied here. Changes must be additive and land in -// saas-proto first. +// The subset of the Temporal Cloud onboarding service that the CLI calls. The +// package, service, RPC and message names form the gRPC method path on the +// wire, so they must match the server exactly. package onboardingservice @@ -32,8 +30,8 @@ const ( // // 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 OnboardingServiceClient interface { - // The endpoint the Temporal CLI signup command polls. - // Same contract as GetOrCreateOnboardingState for a CLI-started session. + // Creates or resumes the caller's onboarding and returns its current state. + // The signup command polls it until onboarding completes. GetOrCreateCLIOnboardingState(ctx context.Context, in *GetOrCreateCLIOnboardingStateRequest, opts ...grpc.CallOption) (*GetOrCreateCLIOnboardingStateResponse, error) } @@ -59,8 +57,8 @@ func (c *onboardingServiceClient) GetOrCreateCLIOnboardingState(ctx context.Cont // All implementations must embed UnimplementedOnboardingServiceServer // for forward compatibility. type OnboardingServiceServer interface { - // The endpoint the Temporal CLI signup command polls. - // Same contract as GetOrCreateOnboardingState for a CLI-started session. + // Creates or resumes the caller's onboarding and returns its current state. + // The signup command polls it until onboarding completes. GetOrCreateCLIOnboardingState(context.Context, *GetOrCreateCLIOnboardingStateRequest) (*GetOrCreateCLIOnboardingStateResponse, error) mustEmbedUnimplementedOnboardingServiceServer() } diff --git a/proto/onboardingservice/v1/onboarding.proto b/proto/onboardingservice/v1/onboarding.proto index 5daf202..1badee6 100644 --- a/proto/onboardingservice/v1/onboarding.proto +++ b/proto/onboardingservice/v1/onboarding.proto @@ -1,10 +1,8 @@ syntax = "proto3"; -// Vendored subset of saas-proto proto/onboardingservice/v1/onboarding.proto. -// saas-proto is the source of truth. Field names, numbers and types must match -// it exactly. Fields the CLI does not need, and that would pull in private -// saas-proto imports, are left out and reserved here; the decoder skips them as -// unknown fields. Changes must be additive and land in saas-proto first. +// The subset of the Temporal Cloud onboarding messages that the CLI uses. Field +// numbers and types must match the server exactly. Fields the CLI doesn't use +// are reserved, and the decoder skips them as unknown fields. package onboardingservice.v1; option go_package = "github.com/temporalio/cloud-cli/internal/onboardingservice/v1;onboardingservice"; @@ -20,20 +18,7 @@ enum StepType { } message OnboardingState { - // Omitted from this copy; the CLI polls on current_step only: - // 2 customer_details_collection - // 3 wait_for_throttle - // 4 stripe_setup - // 5 stripe_setup_intent_confirmation (Stripe client secret) - // 6 wait_for_account_creation - // 8 eligible_promotions - // 9 eligible_billing_plans (private services.saasapi.ui.billingplan.v1 import) - // 10 target_sku_type (temporal.api.cloud.account.beta import) - // 11 billing_provider_details (private api.uiservice.v1 import) reserved 2 to 6, 8 to 11; - reserved "customer_details_collection", "wait_for_throttle", "stripe_setup", - "stripe_setup_intent_confirmation", "wait_for_account_creation", "eligible_promotions", - "eligible_billing_plans", "target_sku_type", "billing_provider_details"; // Indicates the current step of the funnel the user is on StepType current_step = 1; @@ -57,10 +42,7 @@ message GetOrCreateCLIOnboardingStateResponse { } message CustomerDetails { - // Omitted from this copy: 6 agree_terms_of_service and 8 purpose (both deprecated upstream). - // 5 was "Industry", removed upstream. reserved 5, 6, 8; - reserved "agree_terms_of_service", "purpose"; // The first name of the customer. string first_name = 1; @@ -68,7 +50,7 @@ message CustomerDetails { // The last name of the customer. string last_name = 2; - // The name of the company the user is from. If empty, the server defaults to "Personal". + // The name of the company the user is from. string company_name = 3; // The country of the user. diff --git a/proto/onboardingservice/v1/service.proto b/proto/onboardingservice/v1/service.proto index 727f383..00d34ad 100644 --- a/proto/onboardingservice/v1/service.proto +++ b/proto/onboardingservice/v1/service.proto @@ -1,9 +1,8 @@ syntax = "proto3"; -// Vendored subset of saas-proto proto/onboardingservice/v1/service.proto. -// saas-proto is the source of truth. Keep the package, service, RPC and message -// names identical to it: they form the gRPC method path on the wire. Only the -// RPCs the CLI calls are copied here. +// The subset of the Temporal Cloud onboarding service that the CLI calls. The +// package, service, RPC and message names form the gRPC method path on the +// wire, so they must match the server exactly. package onboardingservice.v1; option go_package = "github.com/temporalio/cloud-cli/internal/onboardingservice/v1;onboardingservice"; @@ -11,8 +10,8 @@ option go_package = "github.com/temporalio/cloud-cli/internal/onboardingservice/ import "onboardingservice/v1/onboarding.proto"; service OnboardingService { - // The endpoint the Temporal CLI signup command polls. - // Same contract as GetOrCreateOnboardingState for a CLI-started session. + // Creates or resumes the caller's onboarding and returns its current state. + // The signup command polls it until onboarding completes. rpc GetOrCreateCLIOnboardingState(GetOrCreateCLIOnboardingStateRequest) returns (GetOrCreateCLIOnboardingStateResponse) { } } From 41adba04dc0f72e2f1242e9dcecb4e5b68a3426d Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Wed, 25 Nov 2026 00:43:01 -0500 Subject: [PATCH 12/15] wf --- .github/workflows/build.yml | 4 +++- Makefile | 11 +++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4dea84c..1e80c0b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -26,13 +26,15 @@ jobs: run: echo "$HOME/go/bin" >> $GITHUB_PATH - name: Run commands generation command run: make gen + - name: Run proto generation command + run: make proto - name: Verify no changes were generated run: | # Check if there are any uncommitted changes in the working directory if [ -z "$(git status --porcelain)" ]; then echo "::notice::Generated files are up to date. No changes detected." else - echo "::error::Detected uncommitted changes after running the generation command. Please run the generator and commit the changes." + echo "::error::Detected uncommitted changes after running the generation command. Please run `make gen` and `make proto` and commit the changes." git status git diff exit 1 diff --git a/Makefile b/Makefile index 03de9c5..10bd520 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: all install gen proto build test mocks +.PHONY: all install buf-install gen proto build test mocks # Load .env file if it exists (for local development) # In CI/CD, environment variables are provided by the environment @@ -13,7 +13,7 @@ VERSION := $(shell git describe --tags --always --dirty 2>/dev/null) VERSION_PKG := github.com/temporalio/cloud-cli/temporalcloudcli LDFLAGS := $(if $(VERSION),-X $(VERSION_PKG).Version=$(VERSION)) -all: gen build mocks test +all: gen proto build mocks test # we need to install gen-commands directly because gen-commands does not have its # own go.mod @@ -25,9 +25,12 @@ install: gen: install gen-commands -input ./temporalcloudcli/commands.yml -pkg temporalcloudcli > ./temporalcloudcli/commands.gen.go +buf-install: + go install github.com/bufbuild/buf/cmd/buf@v1.50.0 + # Regenerates the vendored onboarding service client (proto/ -> internal/). -# Requires buf on PATH; the protoc plugins are pinned as go tools in go.mod. -proto: +# The protoc plugins are pinned as go tools in go.mod. +proto: buf-install buf lint buf generate From 648936565a5fae9ca696c65cf30f3757141b9d44 Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Wed, 25 Nov 2026 00:46:09 -0500 Subject: [PATCH 13/15] named ctrl codes --- temporalcloudcli/prompter/select.go | 36 +++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/temporalcloudcli/prompter/select.go b/temporalcloudcli/prompter/select.go index 16977c6..23a2b75 100644 --- a/temporalcloudcli/prompter/select.go +++ b/temporalcloudcli/prompter/select.go @@ -12,10 +12,28 @@ import ( // ErrSelectCanceled is returned when the user cancels a selection (Ctrl-C, Ctrl-D or q). var ErrSelectCanceled = errors.New("selection canceled") +// Input bytes. Raw mode delivers keys as bytes instead of acting on them. const ( keyCtrlC = '\x03' keyCtrlD = '\x04' keyEsc = '\x1b' + + // Arrow keys arrive as ESC, a prefix, then a direction: ESC [ A, or ESC O A + // when the terminal is in application cursor mode. + arrowPrefixCSI = '[' + arrowPrefixSS3 = 'O' + arrowUp = 'A' + arrowDown = 'B' +) + +// Output escape sequences (ANSI/VT100). +const ( + hideCursor = "\x1b[?25l" + showCursor = "\x1b[?25h" + cursorUp = "\x1b[1A" // move the cursor up one line + clearLine = "\x1b[2K" // erase the line the cursor is on + // Raw mode disables output post-processing, so lines must end in \r\n. + newline = "\r\n" ) // fdFile is satisfied by *os.File, the only kind of stream that can be a terminal. @@ -63,9 +81,8 @@ func Select(in io.Reader, out io.Writer, message string, options []string) (int, r := bufio.NewReader(in) selected := 0 - // Raw mode disables output post-processing, so lines end in \r\n. - fmt.Fprintf(out, "\x1b[?25l%s\r\n", message) - defer fmt.Fprint(out, "\x1b[?25h") + fmt.Fprint(out, hideCursor, message, newline) + defer fmt.Fprint(out, showCursor) drawOptions(out, options, selected) for { @@ -80,7 +97,7 @@ func Select(in io.Reader, out io.Writer, message string, options []string) (int, selected = (selected + 1) % len(options) case keyEnter: clearOptions(out, len(options)) - fmt.Fprintf(out, "\x1b[1A\x1b[2K%s %s\r\n", message, options[selected]) + fmt.Fprint(out, cursorUp, clearLine, message, " ", options[selected], newline) return selected, nil case keyCancel: clearOptions(out, len(options)) @@ -121,9 +138,8 @@ func readKey(r *bufio.Reader) (key, error) { case 'j': return keyDown, nil case keyEsc: - // Arrow keys arrive as ESC [ A/B, or ESC O A/B in application cursor mode. prefix, err := r.ReadByte() - if err != nil || (prefix != '[' && prefix != 'O') { + if err != nil || (prefix != arrowPrefixCSI && prefix != arrowPrefixSS3) { return keyOther, nil } code, err := r.ReadByte() @@ -131,9 +147,9 @@ func readKey(r *bufio.Reader) (key, error) { return keyOther, nil } switch code { - case 'A': + case arrowUp: return keyUp, nil - case 'B': + case arrowDown: return keyDown, nil } } @@ -146,13 +162,13 @@ func drawOptions(out io.Writer, options []string, selected int) { if i == selected { marker = "> " } - fmt.Fprintf(out, "%s%s\r\n", marker, opt) + fmt.Fprint(out, marker, opt, newline) } } // clearOptions moves the cursor back over the drawn options and erases them. func clearOptions(out io.Writer, n int) { for range n { - fmt.Fprint(out, "\x1b[1A\x1b[2K") + fmt.Fprint(out, cursorUp, clearLine) } } From c58bba6bbb1833b9fcfa3cdbbf098767e88095e8 Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Wed, 25 Nov 2026 16:47:38 -0500 Subject: [PATCH 14/15] fix --- go.mod | 2 +- temporalcloudcli/commands.signup.go | 46 +++++++++++++++++++++++------ 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/go.mod b/go.mod index 1cb633a..4d3524c 100644 --- a/go.mod +++ b/go.mod @@ -21,6 +21,7 @@ require ( go.temporal.io/sdk/contrib/envconfig v1.0.0 golang.org/x/oauth2 v0.36.0 golang.org/x/term v0.46.0 + google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa google.golang.org/grpc v1.82.1 google.golang.org/protobuf v1.36.11 ) @@ -79,7 +80,6 @@ require ( golang.org/x/time v0.15.0 // indirect golang.org/x/tools v0.51.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/temporalcloudcli/commands.signup.go b/temporalcloudcli/commands.signup.go index 5487d88..6861260 100644 --- a/temporalcloudcli/commands.signup.go +++ b/temporalcloudcli/commands.signup.go @@ -50,28 +50,39 @@ func (c *CloudSignupCommand) run(cctx *CommandContext, _ []string) error { if c.NoWait { resp, err = client.GetOrCreateCLIOnboardingState(cctx, req) if err != nil { - return fmt.Errorf("failed to get onboarding state: %w", err) + err = fmt.Errorf("failed to get onboarding state: %w", err) } } else { resp, err = onboarding.Wait(cctx, client, req, onboarding.DefaultPollConfig, func(step onboardingservice.StepType) { - if !cctx.JSONOutput { + // The first poll after the server starts the signup can come back without a step yet. + if !cctx.JSONOutput && step != onboardingservice.StepType_STEP_TYPE_UNSPECIFIED { cctx.Printer.Printlnf("Waiting for your account (step: %s)...", step) } }) - if err != nil { - return err + } + if onboarding.RejectionReason(err) == onboarding.ReasonAlreadyOnboarded { + // Not a failure: the user can log in to the account they already have. + if cctx.JSONOutput { + return cctx.Printer.PrintStructured( + &onboardingservice.GetOrCreateCLIOnboardingStateResponse{UserAlreadyExists: true}, + printer.StructuredOptions{}, + ) } + cctx.Printer.Println("You already have a Temporal Cloud account. Run `temporal cloud login` to sign in.") + return nil + } + if err != nil { + return signupRejectionError(err) } if cctx.JSONOutput { return cctx.Printer.PrintStructured(resp, printer.StructuredOptions{}) } - switch { - case resp.GetUserAlreadyExists(): - cctx.Printer.Println("You already have a Temporal Cloud account. Run `temporal cloud login` to sign in.") - case onboarding.IsComplete(resp): + // The server reports a finished signup as user_already_exists; a user who had an account before is + // refused with ALREADY_ONBOARDED instead. + if onboarding.IsComplete(resp) { cctx.Printer.Println("Your Temporal Cloud account is ready. Run `temporal cloud login` to sign in.") - default: + } else { cctx.Printer.Printlnf("Onboarding step: %s", resp.GetState().GetCurrentStep()) } return nil @@ -88,6 +99,23 @@ func (c *CloudSignupCommand) login(cctx *CommandContext, config *oauth2.Config, return token, err } +// signupRejectionMessages are what the user should do when the onboarding +// service refuses the signup for a known reason. +var signupRejectionMessages = map[string]string{ + onboarding.ReasonTrialSignupUnavailable: "sign-up from the CLI isn't available right now; try again later", + onboarding.ReasonBrowserSignupInProgress: "you have a sign-up in progress in the browser; finish it there, then run `temporal cloud login`", + onboarding.ReasonTrialSignupCancelled: "your sign-up was cancelled; contact Temporal support", +} + +// signupRejectionError replaces a known signup refusal with a message saying +// what to do, and returns any other error unchanged. +func signupRejectionError(err error) error { + if msg, ok := signupRejectionMessages[onboarding.RejectionReason(err)]; ok { + return NewFriendlyError(msg, err) + } + return err +} + var loginMethods = []struct { value string label string From 8c3349e6b2d0491aac3f2d1e63a3b536654b87b6 Mon Sep 17 00:00:00 2001 From: Shakeel Rao Date: Wed, 25 Nov 2026 16:47:45 -0500 Subject: [PATCH 15/15] Fix onboarding --- internal/onboarding/rejection.go | 37 +++++++++++++++ internal/onboarding/rejection_test.go | 66 +++++++++++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 internal/onboarding/rejection.go create mode 100644 internal/onboarding/rejection_test.go diff --git a/internal/onboarding/rejection.go b/internal/onboarding/rejection.go new file mode 100644 index 0000000..f61c1cd --- /dev/null +++ b/internal/onboarding/rejection.go @@ -0,0 +1,37 @@ +package onboarding + +import ( + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// Reasons the onboarding service gives, as a google.rpc.ErrorInfo reason on a +// FailedPrecondition, for refusing a CLI signup. +const ( + // ReasonAlreadyOnboarded: the user already had an account before this signup. + ReasonAlreadyOnboarded = "ALREADY_ONBOARDED" + // ReasonTrialSignupUnavailable: CLI signup is turned off. + ReasonTrialSignupUnavailable = "TRIAL_SIGNUP_UNAVAILABLE" + // ReasonBrowserSignupInProgress: the user has a signup running in the browser. + ReasonBrowserSignupInProgress = "BROWSER_SIGNUP_IN_PROGRESS" + // ReasonTrialSignupCancelled: the user's signup was cancelled. + ReasonTrialSignupCancelled = "TRIAL_SIGNUP_CANCELLED" +) + +const errorInfoDomain = "cloud.temporal.io" + +// RejectionReason returns the ErrorInfo reason of a signup refused by the +// onboarding service, or "" when err is not one. err may be wrapped. +func RejectionReason(err error) string { + st, ok := status.FromError(err) + if !ok || st.Code() != codes.FailedPrecondition { + return "" + } + for _, detail := range st.Details() { + if info, ok := detail.(*errdetails.ErrorInfo); ok && info.GetDomain() == errorInfoDomain { + return info.GetReason() + } + } + return "" +} diff --git a/internal/onboarding/rejection_test.go b/internal/onboarding/rejection_test.go new file mode 100644 index 0000000..0480bbf --- /dev/null +++ b/internal/onboarding/rejection_test.go @@ -0,0 +1,66 @@ +package onboarding_test + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/temporalio/cloud-cli/internal/onboarding" +) + +func rejection(t *testing.T, code codes.Code, domain, reason string) error { + t.Helper() + st, err := status.New(code, "refused").WithDetails(&errdetails.ErrorInfo{Domain: domain, Reason: reason}) + require.NoError(t, err) + return st.Err() +} + +func TestRejectionReason(t *testing.T) { + tests := []struct { + name string + err error + expected string + }{ + { + name: "signup rejection", + err: rejection(t, codes.FailedPrecondition, "cloud.temporal.io", onboarding.ReasonAlreadyOnboarded), + expected: onboarding.ReasonAlreadyOnboarded, + }, + { + name: "wrapped signup rejection", + err: fmt.Errorf("failed to get onboarding state: %w", + rejection(t, codes.FailedPrecondition, "cloud.temporal.io", onboarding.ReasonTrialSignupCancelled)), + expected: onboarding.ReasonTrialSignupCancelled, + }, + { + name: "other domain", + err: rejection(t, codes.FailedPrecondition, "example.com", onboarding.ReasonAlreadyOnboarded), + }, + { + name: "other code", + err: rejection(t, codes.PermissionDenied, "cloud.temporal.io", onboarding.ReasonAlreadyOnboarded), + }, + { + name: "no details", + err: status.Error(codes.FailedPrecondition, "refused"), + }, + { + name: "not a grpc error", + err: errors.New("boom"), + }, + { + name: "nil", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expected, onboarding.RejectionReason(tt.err)) + }) + } +}