diff --git a/Documentation/oidc-connector.md b/Documentation/oidc-connector.md index 8171bc373e..a525d81ea2 100644 --- a/Documentation/oidc-connector.md +++ b/Documentation/oidc-connector.md @@ -42,6 +42,12 @@ connectors: # following field. # # basicAuthUnsupported: true + + # Some clients require the possibility to get further user details provided + # by via the UserInfo endpoint. + # + # See: http://openid.net/specs/openid-connect-core-1_0.html#UserInfo + # userInfo: https://www.googleapis.com/oauth2/v3/userinfo # Google supports whitelisting allowed domains when using G Suite # (Google Apps). The following field can be set to a list of domains diff --git a/api/api.pb.go b/api/api.pb.go index 0e9130dc1f..e4194dfc67 100644 --- a/api/api.pb.go +++ b/api/api.pb.go @@ -1,6 +1,5 @@ -// Code generated by protoc-gen-go. +// Code generated by protoc-gen-go. DO NOT EDIT. // source: api/api.proto -// DO NOT EDIT! /* Package api is a generated protocol buffer package. @@ -69,6 +68,55 @@ func (m *Client) String() string { return proto.CompactTextString(m) func (*Client) ProtoMessage() {} func (*Client) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } +func (m *Client) GetId() string { + if m != nil { + return m.Id + } + return "" +} + +func (m *Client) GetSecret() string { + if m != nil { + return m.Secret + } + return "" +} + +func (m *Client) GetRedirectUris() []string { + if m != nil { + return m.RedirectUris + } + return nil +} + +func (m *Client) GetTrustedPeers() []string { + if m != nil { + return m.TrustedPeers + } + return nil +} + +func (m *Client) GetPublic() bool { + if m != nil { + return m.Public + } + return false +} + +func (m *Client) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *Client) GetLogoUrl() string { + if m != nil { + return m.LogoUrl + } + return "" +} + // CreateClientReq is a request to make a client. type CreateClientReq struct { Client *Client `protobuf:"bytes,1,opt,name=client" json:"client,omitempty"` @@ -97,6 +145,13 @@ func (m *CreateClientResp) String() string { return proto.CompactText func (*CreateClientResp) ProtoMessage() {} func (*CreateClientResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } +func (m *CreateClientResp) GetAlreadyExists() bool { + if m != nil { + return m.AlreadyExists + } + return false +} + func (m *CreateClientResp) GetClient() *Client { if m != nil { return m.Client @@ -115,6 +170,13 @@ func (m *DeleteClientReq) String() string { return proto.CompactTextS func (*DeleteClientReq) ProtoMessage() {} func (*DeleteClientReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } +func (m *DeleteClientReq) GetId() string { + if m != nil { + return m.Id + } + return "" +} + // DeleteClientResp determines if the client is deleted successfully. type DeleteClientResp struct { NotFound bool `protobuf:"varint,1,opt,name=not_found,json=notFound" json:"not_found,omitempty"` @@ -125,6 +187,13 @@ func (m *DeleteClientResp) String() string { return proto.CompactText func (*DeleteClientResp) ProtoMessage() {} func (*DeleteClientResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } +func (m *DeleteClientResp) GetNotFound() bool { + if m != nil { + return m.NotFound + } + return false +} + // Password is an email for password mapping managed by the storage. type Password struct { Email string `protobuf:"bytes,1,opt,name=email" json:"email,omitempty"` @@ -139,6 +208,34 @@ func (m *Password) String() string { return proto.CompactTextString(m func (*Password) ProtoMessage() {} func (*Password) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } +func (m *Password) GetEmail() string { + if m != nil { + return m.Email + } + return "" +} + +func (m *Password) GetHash() []byte { + if m != nil { + return m.Hash + } + return nil +} + +func (m *Password) GetUsername() string { + if m != nil { + return m.Username + } + return "" +} + +func (m *Password) GetUserId() string { + if m != nil { + return m.UserId + } + return "" +} + // CreatePasswordReq is a request to make a password. type CreatePasswordReq struct { Password *Password `protobuf:"bytes,1,opt,name=password" json:"password,omitempty"` @@ -166,6 +263,13 @@ func (m *CreatePasswordResp) String() string { return proto.CompactTe func (*CreatePasswordResp) ProtoMessage() {} func (*CreatePasswordResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } +func (m *CreatePasswordResp) GetAlreadyExists() bool { + if m != nil { + return m.AlreadyExists + } + return false +} + // UpdatePasswordReq is a request to modify an existing password. type UpdatePasswordReq struct { // The email used to lookup the password. This field cannot be modified @@ -179,6 +283,27 @@ func (m *UpdatePasswordReq) String() string { return proto.CompactTex func (*UpdatePasswordReq) ProtoMessage() {} func (*UpdatePasswordReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } +func (m *UpdatePasswordReq) GetEmail() string { + if m != nil { + return m.Email + } + return "" +} + +func (m *UpdatePasswordReq) GetNewHash() []byte { + if m != nil { + return m.NewHash + } + return nil +} + +func (m *UpdatePasswordReq) GetNewUsername() string { + if m != nil { + return m.NewUsername + } + return "" +} + // UpdatePasswordResp returns the response from modifying an existing password. type UpdatePasswordResp struct { NotFound bool `protobuf:"varint,1,opt,name=not_found,json=notFound" json:"not_found,omitempty"` @@ -189,6 +314,13 @@ func (m *UpdatePasswordResp) String() string { return proto.CompactTe func (*UpdatePasswordResp) ProtoMessage() {} func (*UpdatePasswordResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} } +func (m *UpdatePasswordResp) GetNotFound() bool { + if m != nil { + return m.NotFound + } + return false +} + // DeletePasswordReq is a request to delete a password. type DeletePasswordReq struct { Email string `protobuf:"bytes,1,opt,name=email" json:"email,omitempty"` @@ -199,6 +331,13 @@ func (m *DeletePasswordReq) String() string { return proto.CompactTex func (*DeletePasswordReq) ProtoMessage() {} func (*DeletePasswordReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} } +func (m *DeletePasswordReq) GetEmail() string { + if m != nil { + return m.Email + } + return "" +} + // DeletePasswordResp returns the response from deleting a password. type DeletePasswordResp struct { NotFound bool `protobuf:"varint,1,opt,name=not_found,json=notFound" json:"not_found,omitempty"` @@ -209,6 +348,13 @@ func (m *DeletePasswordResp) String() string { return proto.CompactTe func (*DeletePasswordResp) ProtoMessage() {} func (*DeletePasswordResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} } +func (m *DeletePasswordResp) GetNotFound() bool { + if m != nil { + return m.NotFound + } + return false +} + // ListPasswordReq is a request to enumerate passwords. type ListPasswordReq struct { } @@ -258,6 +404,20 @@ func (m *VersionResp) String() string { return proto.CompactTextStrin func (*VersionResp) ProtoMessage() {} func (*VersionResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} } +func (m *VersionResp) GetServer() string { + if m != nil { + return m.Server + } + return "" +} + +func (m *VersionResp) GetApi() int32 { + if m != nil { + return m.Api + } + return 0 +} + // RefreshTokenRef contains the metadata for a refresh token that is managed by the storage. type RefreshTokenRef struct { // ID of the refresh token. @@ -272,6 +432,34 @@ func (m *RefreshTokenRef) String() string { return proto.CompactTextS func (*RefreshTokenRef) ProtoMessage() {} func (*RefreshTokenRef) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} } +func (m *RefreshTokenRef) GetId() string { + if m != nil { + return m.Id + } + return "" +} + +func (m *RefreshTokenRef) GetClientId() string { + if m != nil { + return m.ClientId + } + return "" +} + +func (m *RefreshTokenRef) GetCreatedAt() int64 { + if m != nil { + return m.CreatedAt + } + return 0 +} + +func (m *RefreshTokenRef) GetLastUsed() int64 { + if m != nil { + return m.LastUsed + } + return 0 +} + // ListRefreshReq is a request to enumerate the refresh tokens of a user. type ListRefreshReq struct { // The "sub" claim returned in the ID Token. @@ -283,6 +471,13 @@ func (m *ListRefreshReq) String() string { return proto.CompactTextSt func (*ListRefreshReq) ProtoMessage() {} func (*ListRefreshReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} } +func (m *ListRefreshReq) GetUserId() string { + if m != nil { + return m.UserId + } + return "" +} + // ListRefreshResp returns a list of refresh tokens for a user. type ListRefreshResp struct { RefreshTokens []*RefreshTokenRef `protobuf:"bytes,1,rep,name=refresh_tokens,json=refreshTokens" json:"refresh_tokens,omitempty"` @@ -312,6 +507,20 @@ func (m *RevokeRefreshReq) String() string { return proto.CompactText func (*RevokeRefreshReq) ProtoMessage() {} func (*RevokeRefreshReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} } +func (m *RevokeRefreshReq) GetUserId() string { + if m != nil { + return m.UserId + } + return "" +} + +func (m *RevokeRefreshReq) GetClientId() string { + if m != nil { + return m.ClientId + } + return "" +} + // RevokeRefreshResp determines if the refresh token is revoked successfully. type RevokeRefreshResp struct { // Set to true is refresh token was not found and token could not be revoked. @@ -323,6 +532,13 @@ func (m *RevokeRefreshResp) String() string { return proto.CompactTex func (*RevokeRefreshResp) ProtoMessage() {} func (*RevokeRefreshResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20} } +func (m *RevokeRefreshResp) GetNotFound() bool { + if m != nil { + return m.NotFound + } + return false +} + func init() { proto.RegisterType((*Client)(nil), "api.Client") proto.RegisterType((*CreateClientReq)(nil), "api.CreateClientReq") diff --git a/connector/connector.go b/connector/connector.go index c442c54af2..12aa3ed13e 100644 --- a/connector/connector.go +++ b/connector/connector.go @@ -97,3 +97,8 @@ type RefreshConnector interface { // changes since the token was last refreshed. Refresh(ctx context.Context, s Scopes, identity Identity) (Identity, error) } + +// UserInfoConnector represents connectors that support the user info endpoint +type UserInfoConnector interface { + GetUserInfo(connData []byte, user *map[string]interface{}) (err error) +} diff --git a/connector/oidc/oidc.go b/connector/oidc/oidc.go index f0d8daf704..38a2bc094b 100644 --- a/connector/oidc/oidc.go +++ b/connector/oidc/oidc.go @@ -3,6 +3,7 @@ package oidc import ( "context" + "encoding/json" "errors" "fmt" "net/http" @@ -17,6 +18,11 @@ import ( "github.com/coreos/dex/connector" ) +type connectorData struct { + // Store token, even if it eventually expires + AccessToken string `json:"accessToken"` +} + // Config holds configuration options for OpenID Connect logins. type Config struct { Issuer string `json:"issuer"` @@ -36,6 +42,8 @@ type Config struct { // Optional list of whitelisted domains when using Google // If this field is nonempty, only users from a listed domain will be allowed to log in HostedDomains []string `json:"hostedDomains"` + // Userinfo endpoint for Relying Parties that need details about the authenticated user + UserInfoURI string `json:"userInfoURI"` } // Domains that don't support basic auth. golang.org/x/oauth2 has an internal @@ -116,6 +124,7 @@ func (c *Config) Open(id string, logger logrus.FieldLogger) (conn connector.Conn logger: logger, cancel: cancel, hostedDomains: c.HostedDomains, + userInfoURI: c.UserInfoURI, }, nil } @@ -132,6 +141,7 @@ type oidcConnector struct { cancel context.CancelFunc logger logrus.FieldLogger hostedDomains []string + userInfoURI string } func (c *oidcConnector) Close() error { @@ -215,6 +225,17 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide Email: claims.Email, EmailVerified: claims.EmailVerified, } + + // Add AccessToken to user identity for future requests + connData, err := json.Marshal(connectorData{ + AccessToken: token.AccessToken, + }) + if err != nil { + return identity, fmt.Errorf("marshal connector data: %v", err) + } + + identity.ConnectorData = connData + return identity, nil } @@ -222,3 +243,39 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide func (c *oidcConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) { return identity, nil } + +func (c *oidcConnector) GetUserInfo(connData []byte, user *map[string]interface{}) (err error) { + + // Extract Access Token that was stored while the connector handled the OIDC handshake + var cData connectorData + + if err := json.Unmarshal(connData, &cData); err != nil { + c.logger.Errorf("Failed to read connector data : %v", err) + return err + } + + // Format Authorization header to request user info on behalf of the client + authorization := fmt.Sprintf("bearer %s", cData.AccessToken) + // Prepare get request including Authorization header from RP + req, err := http.NewRequest("GET", c.userInfoURI, nil) + + if err != nil { + return fmt.Errorf("Error Creating GET request: %v", err) + } + + req.Header.Add("Accept", `application/json`) + req.Header.Add("Content-Type", `application/json`) + req.Header.Add("Authorization", authorization) + + // Prepare http client to execute get request + client := &http.Client{} + + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("Error Executing GET request: %v", err) + } + + json.NewDecoder(resp.Body).Decode(user) + + return nil +} diff --git a/server/handlers.go b/server/handlers.go index d9700f3029..97fcf9a2b9 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -95,6 +95,7 @@ type discovery struct { Auth string `json:"authorization_endpoint"` Token string `json:"token_endpoint"` Keys string `json:"jwks_uri"` + UserInfo string `json:"userinfo_endpoint"` ResponseTypes []string `json:"response_types_supported"` Subjects []string `json:"subject_types_supported"` IDTokenAlgs []string `json:"id_token_signing_alg_values_supported"` @@ -109,6 +110,7 @@ func (s *Server) discoveryHandler() (http.HandlerFunc, error) { Auth: s.absURL("/auth"), Token: s.absURL("/token"), Keys: s.absURL("/keys"), + UserInfo: s.absURL("/userinfo"), Subjects: []string{"public"}, IDTokenAlgs: []string{string(jose.RS256)}, Scopes: []string{"openid", "email", "groups", "profile", "offline_access"}, @@ -638,6 +640,7 @@ func (s *Server) handleToken(w http.ResponseWriter, r *http.Request) { // handle an access token request https://tools.ietf.org/html/rfc6749#section-4.1.3 func (s *Server) handleAuthCode(w http.ResponseWriter, r *http.Request, client storage.Client) { + code := r.PostFormValue("code") redirectURI := r.PostFormValue("redirect_uri") @@ -657,7 +660,28 @@ func (s *Server) handleAuthCode(w http.ResponseWriter, r *http.Request, client s return } - accessToken := storage.NewID() + token := &internal.AccessToken{ + Subject: authCode.Claims.UserID, + Username: authCode.Claims.Username, + Email: authCode.Claims.Email, + EmailVerified: authCode.Claims.EmailVerified, + Groups: authCode.Claims.Groups, + ConnectorData: string(authCode.ConnectorData), + ConnectorId: authCode.ConnectorID, + Expiry: authCode.Expiry.Unix(), + } + + // The accessToken is build from claims + accessToken, err := internal.Marshal(token) + + // Encrypt access token to hide sensible data + accessToken, err = s.Encrypt(accessToken) + if err != nil { + s.logger.Errorf("Internal server error: %v", err) + s.renderError(w, http.StatusInternalServerError, "Internal server error.") + return + } + idToken, expiry, err := s.newIDToken(client.ID, authCode.Claims, authCode.Scopes, authCode.Nonce, accessToken, authCode.ConnectorID) if err != nil { s.logger.Errorf("failed to create ID token: %v", err) @@ -971,6 +995,7 @@ func (s *Server) writeAccessToken(w http.ResponseWriter, idToken, accessToken, r // TODO(ericchiang): figure out an access token story and support the user info // endpoint. For now use a random value so no one depends on the access_token // holding a specific structure. + resp := struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type"` @@ -995,6 +1020,76 @@ func (s *Server) writeAccessToken(w http.ResponseWriter, idToken, accessToken, r w.Write(data) } +// Handler for the /userinfo endpoint +func (s *Server) handleUserInfo(w http.ResponseWriter, r *http.Request) { + + // Extract token type and token value from Authorization header + authorizationSubstrs := strings.Split(r.Header.Get("Authorization"), " ") + token := authorizationSubstrs[1] + + decryptedToken, err := s.Decrypt(token) + if err != nil { + s.logger.Errorf("Internal server error: %v", err) + s.renderError(w, http.StatusInternalServerError, "Internal server error.") + return + } + + accessToken := new(internal.AccessToken) + if err := internal.Unmarshal(decryptedToken, accessToken); err != nil { + s.logger.Errorf("Failed to unmarshal access token: %v", err) + } + + // Find the connector used in this auth flow + conn, err := s.getConnector(accessToken.ConnectorId) + + if err != nil { + s.logger.Errorf("Failed to get connector with id %q : %v", accessToken.ConnectorId, err) + s.renderError(w, http.StatusBadRequest, "Requested resource does not exist") + return + } + + // Create a flexible map initialized with the existing accessToken data + // If the connector does not implement a GetUserInfo, this map is + // returned as is + user := map[string]interface{}{ + "sub": accessToken.Subject, + "name": accessToken.Username, + "email": accessToken.Email, + "email_verified": accessToken.EmailVerified, + "groups": accessToken.Groups, + "expiry": accessToken.Expiry, + } + + switch conn := conn.Connector.(type) { + // Delegate the responsibility of coming up with the user info + // to the connector if it is a UserInfoConnector + // e.g. oidc connector + case connector.UserInfoConnector: + + connData := []byte(accessToken.ConnectorData) + err = conn.GetUserInfo(connData, &user) + + if err != nil { + s.logger.Errorf("Failed to retrieve user info: %v", err) + } + } + + s.writeUserInfo(w, user) +} + +func (s *Server) writeUserInfo(w http.ResponseWriter, user map[string]interface{}) { + + data, err := json.Marshal(user) + if err != nil { + s.logger.Errorf("failed to marshal access token response: %v", err) + s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + w.Write(data) +} + func (s *Server) renderError(w http.ResponseWriter, status int, description string) { if err := s.templates.err(w, http.StatusText(status), description); err != nil { s.logger.Errorf("Server template error: %v", err) diff --git a/server/internal/types.pb.go b/server/internal/types.pb.go index 835ea56223..2e84a83f5c 100644 --- a/server/internal/types.pb.go +++ b/server/internal/types.pb.go @@ -1,6 +1,5 @@ -// Code generated by protoc-gen-go. +// Code generated by protoc-gen-go. DO NOT EDIT. // source: server/internal/types.proto -// DO NOT EDIT! /* Package internal is a generated protocol buffer package. @@ -13,6 +12,7 @@ It is generated from these files: It has these top-level messages: RefreshToken IDTokenSubject + AccessToken */ package internal @@ -42,6 +42,20 @@ func (m *RefreshToken) String() string { return proto.CompactTextStri func (*RefreshToken) ProtoMessage() {} func (*RefreshToken) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } +func (m *RefreshToken) GetRefreshId() string { + if m != nil { + return m.RefreshId + } + return "" +} + +func (m *RefreshToken) GetToken() string { + if m != nil { + return m.Token + } + return "" +} + // IDTokenSubject represents both the userID and connID which is returned // as the "sub" claim in the ID Token. type IDTokenSubject struct { @@ -54,23 +68,123 @@ func (m *IDTokenSubject) String() string { return proto.CompactTextSt func (*IDTokenSubject) ProtoMessage() {} func (*IDTokenSubject) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } +func (m *IDTokenSubject) GetUserId() string { + if m != nil { + return m.UserId + } + return "" +} + +func (m *IDTokenSubject) GetConnId() string { + if m != nil { + return m.ConnId + } + return "" +} + +// AccessToken used in the /userinfo endpoint implementation +type AccessToken struct { + Subject string `protobuf:"bytes,1,opt,name=subject" json:"subject,omitempty"` + Username string `protobuf:"bytes,2,opt,name=username" json:"username,omitempty"` + Email string `protobuf:"bytes,3,opt,name=email" json:"email,omitempty"` + EmailVerified bool `protobuf:"varint,4,opt,name=email_verified,json=emailVerified" json:"email_verified,omitempty"` + Groups []string `protobuf:"bytes,5,rep,name=groups" json:"groups,omitempty"` + ConnectorData string `protobuf:"bytes,6,opt,name=connector_data,json=connectorData" json:"connector_data,omitempty"` + ConnectorId string `protobuf:"bytes,7,opt,name=connector_id,json=connectorId" json:"connector_id,omitempty"` + // Time at which the access token expires, represented as a unix time. + // + // This is the same value as the id_token. + Expiry int64 `protobuf:"varint,8,opt,name=expiry" json:"expiry,omitempty"` +} + +func (m *AccessToken) Reset() { *m = AccessToken{} } +func (m *AccessToken) String() string { return proto.CompactTextString(m) } +func (*AccessToken) ProtoMessage() {} +func (*AccessToken) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } + +func (m *AccessToken) GetSubject() string { + if m != nil { + return m.Subject + } + return "" +} + +func (m *AccessToken) GetUsername() string { + if m != nil { + return m.Username + } + return "" +} + +func (m *AccessToken) GetEmail() string { + if m != nil { + return m.Email + } + return "" +} + +func (m *AccessToken) GetEmailVerified() bool { + if m != nil { + return m.EmailVerified + } + return false +} + +func (m *AccessToken) GetGroups() []string { + if m != nil { + return m.Groups + } + return nil +} + +func (m *AccessToken) GetConnectorData() string { + if m != nil { + return m.ConnectorData + } + return "" +} + +func (m *AccessToken) GetConnectorId() string { + if m != nil { + return m.ConnectorId + } + return "" +} + +func (m *AccessToken) GetExpiry() int64 { + if m != nil { + return m.Expiry + } + return 0 +} + func init() { proto.RegisterType((*RefreshToken)(nil), "internal.RefreshToken") proto.RegisterType((*IDTokenSubject)(nil), "internal.IDTokenSubject") + proto.RegisterType((*AccessToken)(nil), "internal.AccessToken") } func init() { proto.RegisterFile("server/internal/types.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ - // 157 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2e, 0x4e, 0x2d, 0x2a, - 0x4b, 0x2d, 0xd2, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, 0x4b, 0xcc, 0xd1, 0x2f, 0xa9, 0x2c, 0x48, - 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x80, 0x89, 0x2a, 0x39, 0x73, 0xf1, 0x04, - 0xa5, 0xa6, 0x15, 0xa5, 0x16, 0x67, 0x84, 0xe4, 0x67, 0xa7, 0xe6, 0x09, 0xc9, 0x72, 0x71, 0x15, - 0x41, 0xf8, 0xf1, 0x99, 0x29, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x9c, 0x50, 0x11, 0xcf, - 0x14, 0x21, 0x11, 0x2e, 0xd6, 0x12, 0x90, 0x3a, 0x09, 0x26, 0xb0, 0x0c, 0x84, 0xa3, 0xe4, 0xc4, - 0xc5, 0xe7, 0xe9, 0x02, 0xd6, 0x1f, 0x5c, 0x9a, 0x94, 0x95, 0x9a, 0x5c, 0x22, 0x24, 0xce, 0xc5, - 0x5e, 0x5a, 0x9c, 0x5a, 0x84, 0x30, 0x83, 0x0d, 0xc4, 0xf5, 0x4c, 0x01, 0x49, 0x24, 0xe7, 0xe7, - 0xe5, 0x81, 0x24, 0x20, 0x46, 0xb0, 0x81, 0xb8, 0x9e, 0x29, 0x49, 0x6c, 0x60, 0x97, 0x19, 0x03, - 0x02, 0x00, 0x00, 0xff, 0xff, 0x13, 0xfe, 0x01, 0x37, 0xb8, 0x00, 0x00, 0x00, + // 289 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0x91, 0xcd, 0x4e, 0xeb, 0x30, + 0x10, 0x85, 0x95, 0x9b, 0xdb, 0x24, 0x9d, 0xfe, 0x2c, 0x2c, 0x04, 0x16, 0x08, 0x29, 0x44, 0x42, + 0xca, 0x8a, 0x2e, 0x78, 0x02, 0xa0, 0x9b, 0x6c, 0x03, 0x62, 0x1b, 0xb9, 0xf1, 0x14, 0x0c, 0xad, + 0x1d, 0xd9, 0x4e, 0x45, 0x5f, 0x9d, 0x15, 0xb2, 0x9d, 0xa6, 0xbb, 0x7c, 0x67, 0x66, 0xbe, 0x1c, + 0xc9, 0x70, 0x63, 0x50, 0x1f, 0x50, 0xaf, 0x84, 0xb4, 0xa8, 0x25, 0xdb, 0xad, 0xec, 0xb1, 0x43, + 0xf3, 0xd0, 0x69, 0x65, 0x15, 0xc9, 0x4e, 0x69, 0xf1, 0x02, 0xf3, 0x1a, 0xb7, 0x1a, 0xcd, 0xe7, + 0x9b, 0xfa, 0x46, 0x49, 0x6e, 0x01, 0x74, 0xe0, 0x46, 0x70, 0x1a, 0xe5, 0x51, 0x39, 0xad, 0xa7, + 0x43, 0x52, 0x71, 0x72, 0x01, 0x13, 0xeb, 0xf6, 0xe8, 0x3f, 0x3f, 0x09, 0x50, 0x3c, 0xc3, 0xb2, + 0x5a, 0xfb, 0xfb, 0xd7, 0x7e, 0xf3, 0x85, 0xad, 0x25, 0x57, 0x90, 0xf6, 0x06, 0xf5, 0xd9, 0x91, + 0x38, 0xac, 0xb8, 0x1b, 0xb4, 0x4a, 0x4a, 0x37, 0x08, 0x8a, 0xc4, 0x61, 0xc5, 0x8b, 0xdf, 0x08, + 0x66, 0x4f, 0x6d, 0x8b, 0xc6, 0x84, 0x22, 0x14, 0x52, 0x13, 0x64, 0x83, 0xe1, 0x84, 0xe4, 0x1a, + 0x32, 0x27, 0x93, 0x6c, 0x8f, 0x83, 0x63, 0x64, 0xd7, 0x0f, 0xf7, 0x4c, 0xec, 0x68, 0x1c, 0xfa, + 0x79, 0x20, 0xf7, 0xb0, 0xf4, 0x1f, 0xcd, 0x01, 0xb5, 0xd8, 0x0a, 0xe4, 0xf4, 0x7f, 0x1e, 0x95, + 0x59, 0xbd, 0xf0, 0xe9, 0xfb, 0x10, 0x92, 0x4b, 0x48, 0x3e, 0xb4, 0xea, 0x3b, 0x43, 0x27, 0x79, + 0xec, 0xaa, 0x05, 0x72, 0xe7, 0xae, 0x24, 0xb6, 0x56, 0xe9, 0x86, 0x33, 0xcb, 0x68, 0xe2, 0xed, + 0x8b, 0x31, 0x5d, 0x33, 0xcb, 0xc8, 0x1d, 0xcc, 0xcf, 0x6b, 0x82, 0xd3, 0xd4, 0x2f, 0xcd, 0xc6, + 0xac, 0xf2, 0x7f, 0xc0, 0x9f, 0x4e, 0xe8, 0x23, 0xcd, 0xf2, 0xa8, 0x8c, 0xeb, 0x81, 0x36, 0x89, + 0x7f, 0x96, 0xc7, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xa2, 0x73, 0xfb, 0xb5, 0x01, 0x00, + 0x00, } diff --git a/server/internal/types.proto b/server/internal/types.proto index 87e18f4c23..e50520ec1c 100644 --- a/server/internal/types.proto +++ b/server/internal/types.proto @@ -15,3 +15,19 @@ message IDTokenSubject { string user_id = 1; string conn_id = 2; } + +// AccessToken used in the /userinfo endpoint implementation +message AccessToken { + string subject = 1; + string username = 2; + string email = 3; + bool email_verified = 4; + repeated string groups = 5; + string connector_data = 6; + string connector_id = 7; + + // Time at which the access token expires, represented as a unix time. + // + // This is the same value as the id_token. + int64 expiry = 8; +} diff --git a/server/security.go b/server/security.go new file mode 100644 index 0000000000..31b6ae1680 --- /dev/null +++ b/server/security.go @@ -0,0 +1,74 @@ +package server + +import ( + "fmt" + + jose "gopkg.in/square/go-jose.v2" +) + +// Encrypt encrypts and serializes object +func (s *Server) Encrypt(message string) (string, error) { + keys, err := s.storage.GetKeys() + if err != nil { + return "", fmt.Errorf("failed to get keys: %v", err) + } + + if keys.SigningKeyPub == nil { + return "", fmt.Errorf("no public keys found") + } + + // Instantiate an encrypter using RSA-OAEP with AES128-GCM. An error would + // indicate that the selected algorithm(s) are not currently supported. + encrypter, err := jose.NewEncrypter(jose.A128GCM, jose.Recipient{Algorithm: jose.RSA_OAEP, Key: keys.SigningKeyPub}, nil) + // encrypter, err := jose.NewEncrypter(jose.RSA_OAEP, jose.A128GCM, &keys.SigningKeyPub) + if err != nil { + return "", fmt.Errorf("unable to create encrypter: %v", err) + } + + // Encrypt the incoming string. Calling the encrypter returns an encrypted + // JWE object, which can then be serialized for output afterwards. An error + // would indicate a problem in an underlying cryptographic primitive. + object, err := encrypter.Encrypt([]byte(message)) + if err != nil { + return "", fmt.Errorf("unable to encrypt message: %v", err) + } + + // Serialize the encrypted object using the full serialization format. + // Alternatively you can also use the compact format here by calling + // object.CompactSerialize() instead. + serializedObject, err := object.CompactSerialize() + if err != nil { + return "", fmt.Errorf("unable to serialize encrypted message: %v", err) + } + + return serializedObject, nil +} + +// Decrypt decrupts and deserializes a string +func (s *Server) Decrypt(message string) (string, error) { + keys, err := s.storage.GetKeys() + if err != nil { + return "", fmt.Errorf("failed to get keys: %v", err) + } + + if keys.SigningKey == nil { + return "", fmt.Errorf("no private keys found") + } + + // Parse the serialized, encrypted JWE object. An error would indicate that + // the given input did not represent a valid message. + object, err := jose.ParseEncrypted(message) + if err != nil { + return "", fmt.Errorf("unable to parse encrypted message") + } + + // Decrypt and get back the original message. An error here + // would indicate the the message failed to decrypt, e.g. because the auth + // tag was broken or the message was tampered with. + decrypted, err := object.Decrypt(keys.SigningKey) + if err != nil { + return "", fmt.Errorf("unable to decrypt message: %v", err) + } + + return string(decrypted), nil +} diff --git a/server/server.go b/server/server.go index f915b5acb6..a44a884f15 100644 --- a/server/server.go +++ b/server/server.go @@ -240,6 +240,7 @@ func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy) // TODO(ericchiang): rate limit certain paths based on IP. handleWithCORS("/token", s.handleToken) handleWithCORS("/keys", s.handlePublicKeys) + handleWithCORS("/userinfo", s.handleUserInfo) handleFunc("/auth", s.handleAuthorization) handleFunc("/auth/{connector}", s.handleConnectorLogin) r.HandleFunc(path.Join(issuerURL.Path, "/callback"), func(w http.ResponseWriter, r *http.Request) {