├── .gitignore ├── CONTRIBUTING.md ├── Dockerfile ├── Dockerfile.multistage ├── LICENSE ├── Makefile ├── README.md ├── api └── credstore.pb.go ├── client ├── api.go ├── client.go └── server.go ├── cmd ├── credstore-keygen │ └── main.go └── credstore-tokengen │ └── main.go ├── config └── config.go ├── go.mod ├── go.sum ├── jwt ├── app_token.go ├── auth_token.go └── rpc_token.go ├── main.go ├── proto └── credstore.proto └── server ├── auth_server.go └── credstore_server.go /.gitignore: -------------------------------------------------------------------------------- 1 | stash/ 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution, 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:latest 2 | 3 | RUN set -ex; \ 4 | apk add --no-cache --no-progress --virtual .build-deps git go musl-dev; \ 5 | env GOPATH=/go go get -v github.com/google/credstore; \ 6 | env GOPATH=/go go get -v github.com/google/credstore/cmd/credstore-keygen; \ 7 | env GOPATH=/go go get -v github.com/google/credstore/cmd/credstore-tokengen; \ 8 | install -t /bin /go/bin/credstore /go/bin/credstore-keygen /go/bin/credstore-tokengen; \ 9 | rm -rf /go; \ 10 | apk --no-progress del .build-deps 11 | 12 | CMD ["/bin/credstore", "-listen=0.0.0.0:8000", "-logtostderr", "-signing-key", "data/signing.key", "-config", "data/config.yaml"] 13 | -------------------------------------------------------------------------------- /Dockerfile.multistage: -------------------------------------------------------------------------------- 1 | FROM golang:alpine as builder 2 | RUN apk --update add git 3 | RUN go get -v github.com/google/credstore 4 | RUN go get -v github.com/google/credstore/cmd/credstore-keygen 5 | RUN go get -v github.com/google/credstore/cmd/credstore-tokengen 6 | 7 | FROM alpine:latest 8 | COPY --from=builder /go/bin/credstore /go/bin/credstore-keygen /go/bin/credstore-tokengen /bin/ 9 | CMD ["/bin/credstore", "-listen=0.0.0.0:8000", "-logtostderr", "-signing-key", "data/signing.key", "-config", "data/config.yaml"] 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | api/credstore.pb.go: proto/credstore.proto 2 | mkdir -p api 3 | cd proto && protoc -I/usr/local/include -I. \ 4 | -I${GOPATH}/src \ 5 | -I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ 6 | --go_out=Mgoogle/api/annotations.proto=github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api,plugins=grpc:../api \ 7 | credstore.proto 8 | 9 | run: 10 | go run main.go \ 11 | -listen=127.0.0.1:8008 \ 12 | -logtostderr \ 13 | -signing-key stash/signing.key \ 14 | -config stash/config.yaml 15 | 16 | .PHONY: run 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Credstore 2 | 3 | [![Docker Repository on Quay](https://quay.io/repository/picoprod/credstore/status "Docker Repository on Quay")](https://quay.io/repository/picoprod/credstore) 4 | 5 | **This is not an official Google product** 6 | 7 | Credstore is a centralized server providing authentication-by-proxy model. Users 8 | or services can trade auth tokens for per-service per-rpc tokens. 9 | 10 | ## Sample config 11 | 12 | ```yaml 13 | scopes: 14 | - name: vmregistry-all 15 | service: api.VMRegistry 16 | method: '*' 17 | - name: keyserver-all 18 | service: api.KeyServer 19 | method: '*' 20 | 21 | clients: 22 | - vmregistry 23 | - metaserver 24 | - keyserver 25 | - microdhcpd 26 | 27 | authorizations: 28 | - {client: metaserver, scope: vmregistry-all, via: vmregistry.global.example.com} 29 | - {client: metaserver, scope: keyserver-all, via: keyserver.global.example.com} 30 | - {client: microdhcpd, scope: vmregistry-all, via: vmregistry.global.example.com} 31 | ``` 32 | -------------------------------------------------------------------------------- /api/credstore.pb.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | // Code generated by protoc-gen-go. 20 | // source: credstore.proto 21 | // DO NOT EDIT! 22 | 23 | /* 24 | Package api is a generated protocol buffer package. 25 | 26 | It is generated from these files: 27 | credstore.proto 28 | 29 | It has these top-level messages: 30 | AuthRequest 31 | AuthReply 32 | SigningKeyRequest 33 | SigningKeyReply 34 | GetTokenRequest 35 | GetTokenReply 36 | */ 37 | package api 38 | 39 | import proto "github.com/golang/protobuf/proto" 40 | import fmt "fmt" 41 | import math "math" 42 | 43 | import ( 44 | context "golang.org/x/net/context" 45 | grpc "google.golang.org/grpc" 46 | ) 47 | 48 | // Reference imports to suppress errors if they are not otherwise used. 49 | var _ = proto.Marshal 50 | var _ = fmt.Errorf 51 | var _ = math.Inf 52 | 53 | // This is a compile-time assertion to ensure that this generated file 54 | // is compatible with the proto package it is being compiled against. 55 | // A compilation error at this line likely means your copy of the 56 | // proto package needs to be updated. 57 | const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package 58 | 59 | type AuthRequest struct { 60 | } 61 | 62 | func (m *AuthRequest) Reset() { *m = AuthRequest{} } 63 | func (m *AuthRequest) String() string { return proto.CompactTextString(m) } 64 | func (*AuthRequest) ProtoMessage() {} 65 | func (*AuthRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } 66 | 67 | type AuthReply struct { 68 | // JWT that can be used with other CredStore RPCs. 69 | AuthJwt string `protobuf:"bytes,1,opt,name=auth_jwt,json=authJwt" json:"auth_jwt,omitempty"` 70 | } 71 | 72 | func (m *AuthReply) Reset() { *m = AuthReply{} } 73 | func (m *AuthReply) String() string { return proto.CompactTextString(m) } 74 | func (*AuthReply) ProtoMessage() {} 75 | func (*AuthReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } 76 | 77 | func (m *AuthReply) GetAuthJwt() string { 78 | if m != nil { 79 | return m.AuthJwt 80 | } 81 | return "" 82 | } 83 | 84 | type SigningKeyRequest struct { 85 | } 86 | 87 | func (m *SigningKeyRequest) Reset() { *m = SigningKeyRequest{} } 88 | func (m *SigningKeyRequest) String() string { return proto.CompactTextString(m) } 89 | func (*SigningKeyRequest) ProtoMessage() {} 90 | func (*SigningKeyRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } 91 | 92 | type SigningKeyReply struct { 93 | // DER-encoded public key used to sign JWTs on this server. 94 | SigningKey []byte `protobuf:"bytes,1,opt,name=signing_key,json=signingKey,proto3" json:"signing_key,omitempty"` 95 | } 96 | 97 | func (m *SigningKeyReply) Reset() { *m = SigningKeyReply{} } 98 | func (m *SigningKeyReply) String() string { return proto.CompactTextString(m) } 99 | func (*SigningKeyReply) ProtoMessage() {} 100 | func (*SigningKeyReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } 101 | 102 | func (m *SigningKeyReply) GetSigningKey() []byte { 103 | if m != nil { 104 | return m.SigningKey 105 | } 106 | return nil 107 | } 108 | 109 | type GetTokenRequest struct { 110 | // Target RPC endpoint. 111 | Target string `protobuf:"bytes,1,opt,name=target" json:"target,omitempty"` 112 | } 113 | 114 | func (m *GetTokenRequest) Reset() { *m = GetTokenRequest{} } 115 | func (m *GetTokenRequest) String() string { return proto.CompactTextString(m) } 116 | func (*GetTokenRequest) ProtoMessage() {} 117 | func (*GetTokenRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } 118 | 119 | func (m *GetTokenRequest) GetTarget() string { 120 | if m != nil { 121 | return m.Target 122 | } 123 | return "" 124 | } 125 | 126 | type GetTokenReply struct { 127 | // JWT to use with target RPC. 128 | SessionJwt string `protobuf:"bytes,1,opt,name=session_jwt,json=sessionJwt" json:"session_jwt,omitempty"` 129 | } 130 | 131 | func (m *GetTokenReply) Reset() { *m = GetTokenReply{} } 132 | func (m *GetTokenReply) String() string { return proto.CompactTextString(m) } 133 | func (*GetTokenReply) ProtoMessage() {} 134 | func (*GetTokenReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } 135 | 136 | func (m *GetTokenReply) GetSessionJwt() string { 137 | if m != nil { 138 | return m.SessionJwt 139 | } 140 | return "" 141 | } 142 | 143 | func init() { 144 | proto.RegisterType((*AuthRequest)(nil), "api.AuthRequest") 145 | proto.RegisterType((*AuthReply)(nil), "api.AuthReply") 146 | proto.RegisterType((*SigningKeyRequest)(nil), "api.SigningKeyRequest") 147 | proto.RegisterType((*SigningKeyReply)(nil), "api.SigningKeyReply") 148 | proto.RegisterType((*GetTokenRequest)(nil), "api.GetTokenRequest") 149 | proto.RegisterType((*GetTokenReply)(nil), "api.GetTokenReply") 150 | } 151 | 152 | // Reference imports to suppress errors if they are not otherwise used. 153 | var _ context.Context 154 | var _ grpc.ClientConn 155 | 156 | // This is a compile-time assertion to ensure that this generated file 157 | // is compatible with the grpc package it is being compiled against. 158 | const _ = grpc.SupportPackageIsVersion4 159 | 160 | // Client API for CredStoreAuth service 161 | 162 | type CredStoreAuthClient interface { 163 | // Auth takes in jwt.AppToken (bundled into the binary) and returns a jwt.AppToken, 164 | // useable for other RPCs with credstore. 165 | Auth(ctx context.Context, in *AuthRequest, opts ...grpc.CallOption) (*AuthReply, error) 166 | // Returns the currently used public key. 167 | SigningKey(ctx context.Context, in *SigningKeyRequest, opts ...grpc.CallOption) (*SigningKeyReply, error) 168 | } 169 | 170 | type credStoreAuthClient struct { 171 | cc *grpc.ClientConn 172 | } 173 | 174 | func NewCredStoreAuthClient(cc *grpc.ClientConn) CredStoreAuthClient { 175 | return &credStoreAuthClient{cc} 176 | } 177 | 178 | func (c *credStoreAuthClient) Auth(ctx context.Context, in *AuthRequest, opts ...grpc.CallOption) (*AuthReply, error) { 179 | out := new(AuthReply) 180 | err := grpc.Invoke(ctx, "/api.CredStoreAuth/Auth", in, out, c.cc, opts...) 181 | if err != nil { 182 | return nil, err 183 | } 184 | return out, nil 185 | } 186 | 187 | func (c *credStoreAuthClient) SigningKey(ctx context.Context, in *SigningKeyRequest, opts ...grpc.CallOption) (*SigningKeyReply, error) { 188 | out := new(SigningKeyReply) 189 | err := grpc.Invoke(ctx, "/api.CredStoreAuth/SigningKey", in, out, c.cc, opts...) 190 | if err != nil { 191 | return nil, err 192 | } 193 | return out, nil 194 | } 195 | 196 | // Server API for CredStoreAuth service 197 | 198 | type CredStoreAuthServer interface { 199 | // Auth takes in jwt.AppToken (bundled into the binary) and returns a jwt.AppToken, 200 | // useable for other RPCs with credstore. 201 | Auth(context.Context, *AuthRequest) (*AuthReply, error) 202 | // Returns the currently used public key. 203 | SigningKey(context.Context, *SigningKeyRequest) (*SigningKeyReply, error) 204 | } 205 | 206 | func RegisterCredStoreAuthServer(s *grpc.Server, srv CredStoreAuthServer) { 207 | s.RegisterService(&_CredStoreAuth_serviceDesc, srv) 208 | } 209 | 210 | func _CredStoreAuth_Auth_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 211 | in := new(AuthRequest) 212 | if err := dec(in); err != nil { 213 | return nil, err 214 | } 215 | if interceptor == nil { 216 | return srv.(CredStoreAuthServer).Auth(ctx, in) 217 | } 218 | info := &grpc.UnaryServerInfo{ 219 | Server: srv, 220 | FullMethod: "/api.CredStoreAuth/Auth", 221 | } 222 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 223 | return srv.(CredStoreAuthServer).Auth(ctx, req.(*AuthRequest)) 224 | } 225 | return interceptor(ctx, in, info, handler) 226 | } 227 | 228 | func _CredStoreAuth_SigningKey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 229 | in := new(SigningKeyRequest) 230 | if err := dec(in); err != nil { 231 | return nil, err 232 | } 233 | if interceptor == nil { 234 | return srv.(CredStoreAuthServer).SigningKey(ctx, in) 235 | } 236 | info := &grpc.UnaryServerInfo{ 237 | Server: srv, 238 | FullMethod: "/api.CredStoreAuth/SigningKey", 239 | } 240 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 241 | return srv.(CredStoreAuthServer).SigningKey(ctx, req.(*SigningKeyRequest)) 242 | } 243 | return interceptor(ctx, in, info, handler) 244 | } 245 | 246 | var _CredStoreAuth_serviceDesc = grpc.ServiceDesc{ 247 | ServiceName: "api.CredStoreAuth", 248 | HandlerType: (*CredStoreAuthServer)(nil), 249 | Methods: []grpc.MethodDesc{ 250 | { 251 | MethodName: "Auth", 252 | Handler: _CredStoreAuth_Auth_Handler, 253 | }, 254 | { 255 | MethodName: "SigningKey", 256 | Handler: _CredStoreAuth_SigningKey_Handler, 257 | }, 258 | }, 259 | Streams: []grpc.StreamDesc{}, 260 | Metadata: "credstore.proto", 261 | } 262 | 263 | // Client API for CredStore service 264 | 265 | type CredStoreClient interface { 266 | // GetToken provides a JWT token for remote endpoint based on its DNS name. 267 | GetToken(ctx context.Context, in *GetTokenRequest, opts ...grpc.CallOption) (*GetTokenReply, error) 268 | } 269 | 270 | type credStoreClient struct { 271 | cc *grpc.ClientConn 272 | } 273 | 274 | func NewCredStoreClient(cc *grpc.ClientConn) CredStoreClient { 275 | return &credStoreClient{cc} 276 | } 277 | 278 | func (c *credStoreClient) GetToken(ctx context.Context, in *GetTokenRequest, opts ...grpc.CallOption) (*GetTokenReply, error) { 279 | out := new(GetTokenReply) 280 | err := grpc.Invoke(ctx, "/api.CredStore/GetToken", in, out, c.cc, opts...) 281 | if err != nil { 282 | return nil, err 283 | } 284 | return out, nil 285 | } 286 | 287 | // Server API for CredStore service 288 | 289 | type CredStoreServer interface { 290 | // GetToken provides a JWT token for remote endpoint based on its DNS name. 291 | GetToken(context.Context, *GetTokenRequest) (*GetTokenReply, error) 292 | } 293 | 294 | func RegisterCredStoreServer(s *grpc.Server, srv CredStoreServer) { 295 | s.RegisterService(&_CredStore_serviceDesc, srv) 296 | } 297 | 298 | func _CredStore_GetToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 299 | in := new(GetTokenRequest) 300 | if err := dec(in); err != nil { 301 | return nil, err 302 | } 303 | if interceptor == nil { 304 | return srv.(CredStoreServer).GetToken(ctx, in) 305 | } 306 | info := &grpc.UnaryServerInfo{ 307 | Server: srv, 308 | FullMethod: "/api.CredStore/GetToken", 309 | } 310 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 311 | return srv.(CredStoreServer).GetToken(ctx, req.(*GetTokenRequest)) 312 | } 313 | return interceptor(ctx, in, info, handler) 314 | } 315 | 316 | var _CredStore_serviceDesc = grpc.ServiceDesc{ 317 | ServiceName: "api.CredStore", 318 | HandlerType: (*CredStoreServer)(nil), 319 | Methods: []grpc.MethodDesc{ 320 | { 321 | MethodName: "GetToken", 322 | Handler: _CredStore_GetToken_Handler, 323 | }, 324 | }, 325 | Streams: []grpc.StreamDesc{}, 326 | Metadata: "credstore.proto", 327 | } 328 | 329 | func init() { proto.RegisterFile("credstore.proto", fileDescriptor0) } 330 | 331 | var fileDescriptor0 = []byte{ 332 | // 264 bytes of a gzipped FileDescriptorProto 333 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x64, 0x91, 0x41, 0x4b, 0xc3, 0x40, 334 | 0x10, 0x46, 0x2d, 0x4a, 0x6d, 0xa6, 0xc6, 0xe8, 0x2a, 0x45, 0x73, 0x51, 0xf6, 0x20, 0xea, 0x21, 335 | 0x48, 0x04, 0x4f, 0x5e, 0xa4, 0x07, 0xa1, 0xde, 0x52, 0xef, 0x25, 0xda, 0x21, 0x5d, 0x5b, 0xb2, 336 | 0xeb, 0xee, 0x84, 0xb0, 0xff, 0xbe, 0x64, 0x93, 0xb4, 0xa1, 0x39, 0x85, 0x79, 0x99, 0xf9, 0x66, 337 | 0x1e, 0x0b, 0xc1, 0xaf, 0xc6, 0xa5, 0x21, 0xa9, 0x31, 0x52, 0x5a, 0x92, 0x64, 0xc7, 0xa9, 0x12, 338 | 0xdc, 0x87, 0xf1, 0x47, 0x41, 0xab, 0x04, 0xff, 0x0b, 0x34, 0xc4, 0x1f, 0xc0, 0xab, 0x4b, 0xb5, 339 | 0xb1, 0xec, 0x16, 0x46, 0x69, 0x41, 0xab, 0xc5, 0x5f, 0x49, 0x37, 0x83, 0xfb, 0xc1, 0xa3, 0x97, 340 | 0x9c, 0x56, 0xf5, 0xac, 0x24, 0x7e, 0x05, 0x97, 0x73, 0x91, 0xe5, 0x22, 0xcf, 0xbe, 0xd0, 0xb6, 341 | 0xc3, 0x31, 0x04, 0x5d, 0x58, 0x45, 0xdc, 0xc1, 0xd8, 0xd4, 0x68, 0xb1, 0x46, 0xeb, 0x52, 0xce, 342 | 0x12, 0x30, 0xbb, 0x2e, 0xfe, 0x04, 0xc1, 0x27, 0xd2, 0xb7, 0x5c, 0x63, 0xde, 0xc4, 0xb0, 0x09, 343 | 0x0c, 0x29, 0xd5, 0x19, 0xb6, 0x4b, 0x9b, 0x8a, 0xbf, 0x80, 0xbf, 0x6f, 0x6d, 0xc3, 0xd1, 0x18, 344 | 0x21, 0xf3, 0xce, 0x89, 0xd0, 0xa0, 0x59, 0x49, 0xb1, 0x05, 0x7f, 0xaa, 0x71, 0x39, 0xaf, 0xa4, 345 | 0x2b, 0x2d, 0xf6, 0x0c, 0x27, 0xee, 0x7b, 0x11, 0xa5, 0x4a, 0x44, 0x1d, 0xf1, 0xf0, 0xbc, 0x43, 346 | 0xd4, 0xc6, 0xf2, 0x23, 0xf6, 0x0e, 0xb0, 0xb7, 0x61, 0x13, 0xf7, 0xbf, 0xe7, 0x1c, 0x5e, 0xf7, 347 | 0xb8, 0x9b, 0x8e, 0xa7, 0xe0, 0xed, 0x56, 0xb3, 0x37, 0x18, 0xb5, 0x97, 0xb3, 0x7a, 0xe0, 0xc0, 348 | 0x39, 0x64, 0x07, 0xd4, 0x85, 0xfc, 0x0c, 0xdd, 0x43, 0xbd, 0x6e, 0x03, 0x00, 0x00, 0xff, 0xff, 349 | 0x99, 0x63, 0x48, 0x6d, 0xbb, 0x01, 0x00, 0x00, 350 | } 351 | -------------------------------------------------------------------------------- /client/api.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package client 20 | 21 | import ( 22 | "crypto" 23 | "crypto/x509" 24 | "fmt" 25 | "os" 26 | "strings" 27 | 28 | "github.com/google/go-microservice-helpers/client" 29 | "golang.org/x/net/context" 30 | "google.golang.org/grpc" 31 | 32 | pb "github.com/google/credstore/api" 33 | ) 34 | 35 | // GetSigningKey requests the current signing key from CredStore. 36 | func GetSigningKey(ctx context.Context, conn *grpc.ClientConn, tok string) (crypto.PublicKey, error) { 37 | ctx = WithBearerToken(ctx, tok) 38 | 39 | cli := pb.NewCredStoreAuthClient(conn) 40 | repl, err := cli.SigningKey(ctx, &pb.SigningKeyRequest{}) 41 | if err != nil { 42 | return nil, err 43 | } 44 | 45 | pubkey, err := x509.ParsePKIXPublicKey(repl.GetSigningKey()) 46 | if k, ok := pubkey.(crypto.PublicKey); ok { 47 | return k, nil 48 | } 49 | return nil, fmt.Errorf("cannot parse the public key") 50 | } 51 | 52 | // GetAuthToken returns a session JWT token. 53 | func GetAuthToken(ctx context.Context, conn *grpc.ClientConn, tok string) (string, error) { 54 | ctx = WithBearerToken(ctx, tok) 55 | 56 | cli := pb.NewCredStoreAuthClient(conn) 57 | repl, err := cli.Auth(ctx, &pb.AuthRequest{}) 58 | if err != nil { 59 | return "", err 60 | } 61 | 62 | return repl.GetAuthJwt(), nil 63 | } 64 | 65 | const appTokenEnv = "CREDSTORE_APP_TOKEN" 66 | 67 | // GetAppToken returns the app token for currently running app. 68 | func GetAppToken() (string, error) { 69 | tok := os.Getenv(appTokenEnv) 70 | if tok == "" { 71 | return "", fmt.Errorf("app token not present or malformed") 72 | } 73 | return tok, nil 74 | } 75 | 76 | // GetTokenForRemote returns a JWT token for given remote. 77 | func GetTokenForRemote(ctx context.Context, conn *grpc.ClientConn, sessTok string, target string) (string, error) { 78 | ctx = WithBearerToken(ctx, sessTok) 79 | 80 | cli := pb.NewCredStoreClient(conn) 81 | repl, err := cli.GetToken(ctx, &pb.GetTokenRequest{Target: target}) 82 | if err != nil { 83 | return "", err 84 | } 85 | 86 | return repl.GetSessionJwt(), nil 87 | } 88 | 89 | type CredstoreClient struct { 90 | conn *grpc.ClientConn 91 | appTok string 92 | sessTok string 93 | signingKey crypto.PublicKey 94 | } 95 | 96 | // NewCredstoreClient creates a new CredstoreClient. 97 | func NewCredstoreClient(ctx context.Context, credStoreAddress string, credStoreCA string) (*CredstoreClient, error) { 98 | appTok, err := GetAppToken() 99 | if err != nil { 100 | return nil, fmt.Errorf("failed to get app token: %v", err) 101 | } 102 | 103 | conn, err := clienthelpers.NewGRPCConn(credStoreAddress, credStoreCA, "", "") 104 | if err != nil { 105 | return nil, fmt.Errorf("failed to create connection to credstore: %v", err) 106 | } 107 | 108 | credStoreSessionTok, err := GetAuthToken(ctx, conn, appTok) 109 | if err != nil { 110 | return nil, fmt.Errorf("failed to get session token: %v", err) 111 | } 112 | 113 | credStoreKey, err := GetSigningKey(ctx, conn, appTok) 114 | if err != nil { 115 | return nil, fmt.Errorf("failed to get signing key: %v", err) 116 | } 117 | 118 | return &CredstoreClient{ 119 | conn: conn, 120 | appTok: appTok, 121 | sessTok: credStoreSessionTok, 122 | signingKey: credStoreKey, 123 | }, nil 124 | } 125 | 126 | // SigningKey returns credstore public key for JWT verification. 127 | func (c CredstoreClient) SigningKey() crypto.PublicKey { 128 | return c.signingKey 129 | } 130 | 131 | // GetTokenForRemote returns a token for given remote host:port. 132 | func (c CredstoreClient) GetTokenForRemote(ctx context.Context, remoteHostPort string) (string, error) { 133 | dnsname := strings.Split(remoteHostPort, ":")[0] 134 | return GetTokenForRemote(ctx, c.conn, c.sessTok, dnsname) 135 | } 136 | -------------------------------------------------------------------------------- /client/client.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package client 20 | 21 | import ( 22 | "golang.org/x/net/context" 23 | "google.golang.org/grpc/metadata" 24 | ) 25 | 26 | // WithBearerToken adds bearer token to the context. 27 | func WithBearerToken(ctx context.Context, token string) context.Context { 28 | md, ok := metadata.FromOutgoingContext(ctx) 29 | if !ok { 30 | md = metadata.New(nil) 31 | } else { 32 | md = md.Copy() 33 | } 34 | 35 | md["authorization"] = []string{"bearer " + token} 36 | 37 | ctx = metadata.NewOutgoingContext(ctx, md) 38 | 39 | return ctx 40 | } 41 | -------------------------------------------------------------------------------- /client/server.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | // Package client provides helper APIs for clients. 20 | // 21 | // Based on https://github.com/grpc-ecosystem/go-grpc-middleware/tree/master/auth, licensed under Apache-2.0 22 | package client 23 | 24 | import ( 25 | "crypto" 26 | "encoding/json" 27 | "strings" 28 | 29 | "github.com/google/credstore/jwt" 30 | 31 | "golang.org/x/net/context" 32 | "google.golang.org/grpc" 33 | "google.golang.org/grpc/codes" 34 | "google.golang.org/grpc/metadata" 35 | jose "gopkg.in/square/go-jose.v2" 36 | ) 37 | 38 | type tokenKeyType struct{} 39 | 40 | // TokenKey is the context key for token interceptor payload 41 | var TokenKey = tokenKeyType{} 42 | 43 | // CredStoreTokenInterceptor returns a new unary server interceptor that performs per-request auth. 44 | func CredStoreTokenInterceptor(publicKey crypto.PublicKey) grpc.UnaryServerInterceptor { 45 | return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { 46 | var newCtx context.Context 47 | var err error 48 | 49 | md, ok := metadata.FromIncomingContext(ctx) 50 | if ok == false { 51 | return nil, grpc.Errorf(codes.Unauthenticated, "cannot read metadata for request") 52 | } 53 | 54 | tok := md["authorization"] 55 | if len(tok) != 1 { 56 | return nil, grpc.Errorf(codes.Unauthenticated, "bad authorization string") 57 | } 58 | if tok[0] == "" { 59 | return nil, grpc.Errorf(codes.Unauthenticated, "authorization header is missing") 60 | } 61 | 62 | splits := strings.SplitN(tok[0], " ", 2) 63 | if len(splits) < 2 { 64 | return nil, grpc.Errorf(codes.Unauthenticated, "bad authorization string") 65 | } 66 | 67 | if strings.ToLower(splits[0]) != strings.ToLower("bearer") { 68 | return nil, grpc.Errorf(codes.Unauthenticated, "request unauthenticated with 'bearer'") 69 | } 70 | 71 | jwtTokString := splits[1] 72 | jwtTok, err := jose.ParseSigned(jwtTokString) 73 | if err != nil { 74 | return nil, grpc.Errorf(codes.Unauthenticated, "failed to parse token: %v", err) 75 | } 76 | 77 | jwtPayload, err := jwtTok.Verify(publicKey) 78 | if err != nil { 79 | return nil, grpc.Errorf(codes.Unauthenticated, "failed to verify token: %v", err) 80 | } 81 | 82 | newCtx = context.WithValue(ctx, TokenKey, jwtPayload) 83 | 84 | if err != nil { 85 | return nil, err 86 | } 87 | return handler(newCtx, req) 88 | } 89 | } 90 | 91 | // CredStoreMethodAuthInterceptor returns a new unary server interceptor that verifies rpc token. 92 | func CredStoreMethodAuthInterceptor() grpc.UnaryServerInterceptor { 93 | return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { 94 | jwtTokString := ctx.Value(TokenKey).([]byte) 95 | var jwtTok jwt.RPCToken 96 | err := json.Unmarshal(jwtTokString, &jwtTok) 97 | if err != nil { 98 | return nil, grpc.Errorf(codes.Unauthenticated, "cannot deserialize JWT token: %v", err) 99 | } 100 | 101 | if err := jwtTok.Verify(); err != nil { 102 | return nil, grpc.Errorf(codes.Unauthenticated, "cannot verify JWT token: %v", err) 103 | } 104 | 105 | splits := strings.SplitN(info.FullMethod, "/", 3) 106 | if len(splits) != 3 { 107 | return nil, grpc.Errorf(codes.Internal, "failed to split method %s", info.FullMethod) 108 | } 109 | 110 | if jwtTok.Service != splits[1] { 111 | return nil, grpc.Errorf(codes.PermissionDenied, "not authrized to access service %s", jwtTok.Service) 112 | } 113 | 114 | if jwtTok.Method != "*" { 115 | if jwtTok.Method != splits[2] { 116 | return nil, grpc.Errorf(codes.PermissionDenied, "not authrized to access method %s of service %s", jwtTok.Method, jwtTok.Service) 117 | } 118 | } 119 | 120 | return handler(ctx, req) 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /cmd/credstore-keygen/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package main 20 | 21 | import ( 22 | "crypto/ecdsa" 23 | "crypto/elliptic" 24 | "crypto/rand" 25 | "crypto/x509" 26 | "encoding/pem" 27 | "os" 28 | 29 | "github.com/golang/glog" 30 | ) 31 | 32 | func main() { 33 | defer glog.Flush() 34 | 35 | privkey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) 36 | if err != nil { 37 | glog.Fatalf("failed to generate a keypair: %v", err) 38 | } 39 | 40 | privkeyBytes, err := x509.MarshalECPrivateKey(privkey) 41 | if err != nil { 42 | glog.Fatalf("failed to marshal ec key: %v", err) 43 | } 44 | 45 | err = pem.Encode(os.Stdout, &pem.Block{ 46 | Type: "EC PRIVATE KEY", 47 | Bytes: privkeyBytes, 48 | }) 49 | if err != nil { 50 | glog.Fatalf("failed to encode ec key: %v", err) 51 | } 52 | 53 | pubkeyBytes, err := x509.MarshalPKIXPublicKey(privkey.Public()) 54 | if err != nil { 55 | glog.Fatalf("failed to marshal ec public key: %v", err) 56 | } 57 | 58 | err = pem.Encode(os.Stdout, &pem.Block{Type: "EC PUBLIC KEY", Bytes: pubkeyBytes}) 59 | if err != nil { 60 | glog.Fatalf("failed to encode ec public key: %v", err) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /cmd/credstore-tokengen/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package main 20 | 21 | import ( 22 | "flag" 23 | "fmt" 24 | 25 | "github.com/google/credstore/jwt" 26 | "github.com/google/go-microservice-helpers/pki" 27 | 28 | "github.com/golang/glog" 29 | jose "gopkg.in/square/go-jose.v2" 30 | ) 31 | 32 | var ( 33 | clientName = flag.String("client", "", "client name") 34 | signingKeyFile = flag.String("signing-key", "", "path to a signing private key") 35 | longFormTok = flag.Bool("long", false, "generate long form token") 36 | ) 37 | 38 | func main() { 39 | flag.Parse() 40 | defer glog.Flush() 41 | 42 | if *clientName == "" { 43 | glog.Fatalf("client name not specified") 44 | } 45 | 46 | if *signingKeyFile == "" { 47 | glog.Fatalf("signing key file not specified") 48 | } 49 | 50 | signingKey, err := pki.LoadECKeyFromFile(*signingKeyFile) 51 | if err != nil { 52 | glog.Fatalf("failed to load signing key file: %v", err) 53 | } 54 | 55 | signer, err := jose.NewSigner( 56 | jose.SigningKey{Algorithm: jose.ES384, Key: signingKey}, 57 | &jose.SignerOptions{ 58 | ExtraHeaders: map[jose.HeaderKey]interface{}{"typ": "JWT"}, 59 | }) 60 | if err != nil { 61 | glog.Fatalf("failed to create JWT signer: %v", err) 62 | } 63 | 64 | payload, err := jwt.BuildAppToken(*clientName) 65 | if err != nil { 66 | glog.Fatalf("failed to create JWT token: %v", err) 67 | } 68 | 69 | object, err := signer.Sign(payload) 70 | if err != nil { 71 | glog.Fatalf("failed to sign JWT payload: %v", err) 72 | } 73 | 74 | var serialized string 75 | if *longFormTok { 76 | serialized = object.FullSerialize() 77 | } else { 78 | serialized, err = object.CompactSerialize() 79 | if err != nil { 80 | glog.Fatalf("failed to serialize short-form token: %v", err) 81 | } 82 | } 83 | fmt.Println(serialized) 84 | } 85 | -------------------------------------------------------------------------------- /config/config.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package config 20 | 21 | import ( 22 | "io/ioutil" 23 | 24 | "gopkg.in/yaml.v2" 25 | ) 26 | 27 | type Scope struct { 28 | Name string `yaml:"name"` 29 | Service string `yaml:"service"` 30 | Method string `yaml:"method"` 31 | } 32 | 33 | type Authorization struct { 34 | Client string `yaml:"client"` 35 | Scope string `yaml:"scope"` 36 | Via string `yaml:"via"` 37 | } 38 | 39 | type Config struct { 40 | Scopes []Scope `yaml:"scopes"` 41 | Clients []string `yaml:"clients"` 42 | Authorizations []Authorization `yaml:"authorizations"` 43 | } 44 | 45 | func LoadConfig(fileName string) (*Config, error) { 46 | data, err := ioutil.ReadFile(fileName) 47 | if err != nil { 48 | return nil, err 49 | } 50 | 51 | var cfg Config 52 | err = yaml.Unmarshal(data, &cfg) 53 | if err != nil { 54 | return nil, err 55 | } 56 | return &cfg, nil 57 | } 58 | 59 | func (c Config) FindClient(name string) bool { 60 | for _, cli := range c.Clients { 61 | if cli == name { 62 | return true 63 | } 64 | } 65 | return false 66 | } 67 | 68 | func (c Config) FindAuthorization(client, target string) string { 69 | for _, a := range c.Authorizations { 70 | if a.Client == client && a.Via == target { 71 | return a.Scope 72 | } 73 | } 74 | return "" 75 | } 76 | 77 | func (c Config) FindScope(name string) *Scope { 78 | for _, s := range c.Scopes { 79 | if s.Name == name { 80 | return &s 81 | } 82 | } 83 | return nil 84 | } 85 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/google/credstore 2 | 3 | require ( 4 | github.com/DataDog/zstd v1.3.4 // indirect 5 | github.com/Shopify/sarama v1.20.0 // indirect 6 | github.com/Shopify/toxiproxy v2.1.3+incompatible // indirect 7 | github.com/apache/thrift v0.0.0-20181217171848-56ac72e74ae3 // indirect 8 | github.com/davecgh/go-spew v1.1.1 // indirect 9 | github.com/eapache/go-resiliency v1.1.0 // indirect 10 | github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 // indirect 11 | github.com/eapache/queue v1.1.0 // indirect 12 | github.com/go-logfmt/logfmt v0.4.0 // indirect 13 | github.com/gogo/protobuf v1.2.0 // indirect 14 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b 15 | github.com/golang/protobuf v1.2.0 16 | github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect 17 | github.com/google/go-microservice-helpers v0.0.0-20170611213619-4a88aaa13aa1 18 | github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 19 | github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect 20 | github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645 21 | github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492 // indirect 22 | github.com/opentracing/opentracing-go v1.0.2 23 | github.com/openzipkin/zipkin-go-opentracing v0.3.4 // indirect 24 | github.com/pierrec/lz4 v2.0.5+incompatible // indirect 25 | github.com/pmezard/go-difflib v1.0.0 // indirect 26 | github.com/prometheus/client_golang v0.9.2 // indirect 27 | github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a // indirect 28 | github.com/stretchr/testify v1.2.2 // indirect 29 | golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 // indirect 30 | golang.org/x/net v0.0.0-20181217023233-e147a9138326 31 | google.golang.org/grpc v1.17.0 32 | gopkg.in/square/go-jose.v2 v2.2.1 33 | gopkg.in/yaml.v2 v2.2.2 34 | ) 35 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 2 | github.com/DataDog/zstd v1.3.4 h1:LAGHkXuvC6yky+C2CUG2tD7w8QlrUwpue8XwIh0X4AY= 3 | github.com/DataDog/zstd v1.3.4/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= 4 | github.com/Shopify/sarama v1.20.0 h1:wAMHhl1lGRlobeoV/xOKpbqD2OQsOvY4A/vIOGroIe8= 5 | github.com/Shopify/sarama v1.20.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= 6 | github.com/Shopify/toxiproxy v2.1.3+incompatible h1:awiJqUYH4q4OmoBiRccJykjd7B+w0loJi2keSna4X/M= 7 | github.com/Shopify/toxiproxy v2.1.3+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= 8 | github.com/apache/thrift v0.0.0-20181217171848-56ac72e74ae3 h1:3eCDtvUVYYF/ru4C4gNTN+MdklfV42BigzFWc4xDY4E= 9 | github.com/apache/thrift v0.0.0-20181217171848-56ac72e74ae3/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= 10 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 h1:xJ4a3vCFaGF/jqvzLMYoU8P317H5OQ+Via4RmuPwCS0= 11 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= 12 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= 13 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 14 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 15 | github.com/eapache/go-resiliency v1.1.0 h1:1NtRmCAqadE2FN4ZcN6g90TP3uk8cg9rn9eNK2197aU= 16 | github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= 17 | github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 h1:YEetp8/yCZMuEPMUDHG0CW/brkkEp8mzqk2+ODEitlw= 18 | github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= 19 | github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc= 20 | github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= 21 | github.com/go-logfmt/logfmt v0.4.0 h1:MP4Eh7ZCb31lleYCFuwm0oe4/YGak+5l1vA2NOE80nA= 22 | github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= 23 | github.com/gogo/protobuf v1.2.0 h1:xU6/SpYbvkNYiptHJYEDRseDLvYE7wSqhYYNy0QSUzI= 24 | github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= 25 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= 26 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= 27 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= 28 | github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= 29 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 30 | github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db h1:woRePGFeVFfLKN/pOkfl+p/TAqKOfFu+7KPlMVpok/w= 31 | github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 32 | github.com/google/go-microservice-helpers v0.0.0-20170611213619-4a88aaa13aa1 h1:vqwVbEOWA+K+sAHbF3DoxHUEZQ1kZ3oWXvz1oJGapKA= 33 | github.com/google/go-microservice-helpers v0.0.0-20170611213619-4a88aaa13aa1/go.mod h1:CRQ7hS5Tr5dVEHYs6JhcdygxqlhDxiPmYvZGQDyeZvM= 34 | github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 h1:BWIsLfhgKhV5g/oF34aRjniBHLTZe5DNekSjbAjIS6c= 35 | github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= 36 | github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= 37 | github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= 38 | github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645 h1:MJG/KsmcqMwFAkh8mTnAwhyKoB+sTAnY4CACC110tbU= 39 | github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645/go.mod h1:6iZfnjpejD4L/4DwD7NryNaJyCQdzwWwH2MWhCA90Kw= 40 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= 41 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515 h1:T+h1c/A9Gawja4Y9mFVWj2vyii2bbUNDw3kt9VxK2EY= 42 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= 43 | github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= 44 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= 45 | github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492 h1:lM6RxxfUMrYL/f8bWEUqdXrANWtrL7Nndbm9iFN0DlU= 46 | github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis= 47 | github.com/opentracing/opentracing-go v1.0.2 h1:3jA2P6O1F9UOrWVpwrIo17pu01KWvNWg4X946/Y5Zwg= 48 | github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= 49 | github.com/openzipkin/zipkin-go-opentracing v0.3.4 h1:x/pBv/5VJNWkcHF1G9xqhug8Iw7X1y1zOMzDmyuvP2g= 50 | github.com/openzipkin/zipkin-go-opentracing v0.3.4/go.mod h1:js2AbwmHW0YD9DwIw2JhQWmbfFi/UnWyYwdVhqbCDOE= 51 | github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= 52 | github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= 53 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 54 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 55 | github.com/prometheus/client_golang v0.9.2 h1:awm861/B8OKDd2I/6o1dy3ra4BamzKhYOiGItCeZ740= 56 | github.com/prometheus/client_golang v0.9.2/go.mod h1:OsXs2jCmiKlQ1lTBmv21f2mNfw4xf/QclQDMrYNZzcM= 57 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 h1:idejC8f05m9MGOsuEi1ATq9shN03HrxNkD/luQvxCv8= 58 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 59 | github.com/prometheus/common v0.0.0-20181126121408-4724e9255275 h1:PnBWHBf+6L0jOqq0gIVUe6Yk0/QMZ640k6NvkxcBf+8= 60 | github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= 61 | github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a h1:9a8MnZMP0X2nLJdBg+pBmGgkJlSaKC2KaQmTCk1XDtE= 62 | github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 63 | github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a h1:9ZKAASQSHhDYGoxY8uLVpewe1GDZ2vu2Tr/vTdVAkFQ= 64 | github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= 65 | github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= 66 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 67 | golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 h1:mKdxBk7AujPs8kU4m80U72y/zjbZ3UcXC7dClwKbUI0= 68 | golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 69 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= 70 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 71 | golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 72 | golang.org/x/net v0.0.0-20181217023233-e147a9138326 h1:iCzOf0xz39Tstp+Tu/WwyGjUXCk34QhQORRxBeXXTA4= 73 | golang.org/x/net v0.0.0-20181217023233-e147a9138326/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 74 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= 75 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= 76 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 77 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f h1:Bl/8QSvNqXvPGPGXa2z5xUTmV7VDcZyvRZ+QQXkXTZQ= 78 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 79 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522 h1:Ve1ORMCxvRmSXBwJK+t3Oy+V2vRW2OetUQBq4rJIkZE= 80 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 81 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= 82 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 83 | golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 84 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= 85 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc= 86 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= 87 | google.golang.org/grpc v1.17.0 h1:TRJYBgMclJvGYn2rIMjj+h9KtMt5r1Ij7ODVRIZkwhk= 88 | google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= 89 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 90 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 91 | gopkg.in/square/go-jose.v2 v2.2.1 h1:uRIz/V7RfMsMgGnCp+YybIdstDIz8wc0H283wHQfwic= 92 | gopkg.in/square/go-jose.v2 v2.2.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= 93 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 94 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 95 | honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 96 | -------------------------------------------------------------------------------- /jwt/app_token.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package jwt 20 | 21 | import ( 22 | "encoding/json" 23 | "fmt" 24 | ) 25 | 26 | // TokenKindAapp is a token used to auth to CredStore. 27 | const TokenKindAapp = "app" 28 | 29 | // AppToken is JWT session token for CredStore. 30 | type AppToken struct { 31 | Client string `json:"cli"` 32 | Kind string `json:"kind"` 33 | } 34 | 35 | // Verify verifies token structure. 36 | func (tok AppToken) Verify() error { 37 | if tok.Kind != TokenKindAapp { 38 | return fmt.Errorf("expected app token, got %s token", tok.Kind) 39 | } 40 | return nil 41 | } 42 | 43 | // BuildAppToken creates and serializes a session token. 44 | func BuildAppToken(client string) ([]byte, error) { 45 | tok := AppToken{ 46 | Client: client, 47 | Kind: TokenKindAapp, 48 | } 49 | 50 | return json.Marshal(tok) 51 | } 52 | -------------------------------------------------------------------------------- /jwt/auth_token.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package jwt 20 | 21 | import ( 22 | "encoding/json" 23 | "fmt" 24 | ) 25 | 26 | // TokenKindAuth is a token used to query CredStore. 27 | const TokenKindAuth = "auth" 28 | 29 | // AuthToken is JWT session token for CredStore. 30 | type AuthToken struct { 31 | Client string `json:"cli"` 32 | Kind string `json:"kind"` 33 | } 34 | 35 | // Verify verifies token structure. 36 | func (tok AuthToken) Verify() error { 37 | if tok.Kind != TokenKindAuth { 38 | return fmt.Errorf("expected auth token, got %s token", tok.Kind) 39 | } 40 | return nil 41 | } 42 | 43 | // BuildAuthToken creates and serializes a session token. 44 | func BuildAuthToken(client string) ([]byte, error) { 45 | tok := AuthToken{ 46 | Client: client, 47 | Kind: TokenKindAuth, 48 | } 49 | 50 | return json.Marshal(tok) 51 | } 52 | -------------------------------------------------------------------------------- /jwt/rpc_token.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package jwt 20 | 21 | import ( 22 | "encoding/json" 23 | "fmt" 24 | ) 25 | 26 | // TokenKindRPC is a token used to query CredStore. 27 | const TokenKindRPC = "rpc" 28 | 29 | // RPCToken is JWT token to access other services. 30 | type RPCToken struct { 31 | Client string `json:"cli"` 32 | Kind string `json:"kind"` 33 | Service string `json:"svc"` 34 | Method string `json:"meth"` 35 | } 36 | 37 | // Verify verifies token structure. 38 | func (tok RPCToken) Verify() error { 39 | if tok.Kind != TokenKindRPC { 40 | return fmt.Errorf("expected rpc token, got %s token", tok.Kind) 41 | } 42 | return nil 43 | } 44 | 45 | // BuildRPCToken creates and serializes a session token. 46 | func BuildRPCToken(client, service, method string) ([]byte, error) { 47 | tok := RPCToken{ 48 | Client: client, 49 | Kind: TokenKindRPC, 50 | Service: service, 51 | Method: method, 52 | } 53 | 54 | return json.Marshal(tok) 55 | } 56 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package main 20 | 21 | import ( 22 | "flag" 23 | 24 | pb "github.com/google/credstore/api" 25 | "github.com/google/credstore/client" 26 | "github.com/google/credstore/config" 27 | "github.com/google/credstore/server" 28 | "github.com/google/go-microservice-helpers/pki" 29 | mlpserver "github.com/google/go-microservice-helpers/server" 30 | "github.com/google/go-microservice-helpers/tracing" 31 | "github.com/golang/glog" 32 | "github.com/grpc-ecosystem/go-grpc-middleware" 33 | "github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc" 34 | opentracing "github.com/opentracing/opentracing-go" 35 | "google.golang.org/grpc" 36 | "google.golang.org/grpc/reflection" 37 | ) 38 | 39 | var ( 40 | configFile = flag.String("config", "", "path to a config file") 41 | signingKeyFile = flag.String("signing-key", "", "path to a signing private key") 42 | ) 43 | 44 | func main() { 45 | flag.Parse() 46 | defer glog.Flush() 47 | 48 | err := tracing.InitTracer(*mlpserver.ListenAddress, "credstore") 49 | if err != nil { 50 | glog.Fatalf("failed to init tracing interface: %v", err) 51 | } 52 | 53 | signingKey, err := pki.LoadECKeyFromFile(*signingKeyFile) 54 | if err != nil { 55 | glog.Fatalf("failed to load signing key file: %v", err) 56 | } 57 | 58 | cfg, err := config.LoadConfig(*configFile) 59 | if err != nil { 60 | glog.Fatalf("failed to load config: %v", err) 61 | } 62 | 63 | authSvr, err := server.NewAuthServer(signingKey, cfg) 64 | if err != nil { 65 | glog.Fatalf("failed to create auth server: %v", err) 66 | } 67 | 68 | credServer, err := server.NewCredStoreServer(signingKey, cfg) 69 | if err != nil { 70 | glog.Fatalf("failed to create cred store server: %v", err) 71 | } 72 | 73 | grpcServer := grpc.NewServer( 74 | grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer( 75 | otgrpc.OpenTracingServerInterceptor(opentracing.GlobalTracer()), 76 | client.CredStoreTokenInterceptor(signingKey.Public()), 77 | server.CredStoreServerInterceptor(), 78 | server.AuthServerInterceptor(), 79 | ))) 80 | pb.RegisterCredStoreAuthServer(grpcServer, authSvr) 81 | pb.RegisterCredStoreServer(grpcServer, credServer) 82 | reflection.Register(grpcServer) 83 | 84 | err = mlpserver.ListenAndServe(grpcServer, nil) 85 | if err != nil { 86 | glog.Fatalf("failed to serve: %v", err) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /proto/credstore.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package api; 3 | 4 | message AuthRequest {} 5 | 6 | message AuthReply { 7 | // JWT that can be used with other CredStore RPCs. 8 | string auth_jwt = 1; 9 | } 10 | 11 | message SigningKeyRequest {} 12 | 13 | message SigningKeyReply { 14 | // DER-encoded public key used to sign JWTs on this server. 15 | bytes signing_key = 1; 16 | } 17 | 18 | service CredStoreAuth { 19 | // Auth takes in jwt.AppToken (bundled into the binary) and returns a jwt.AppToken, 20 | // useable for other RPCs with credstore. 21 | rpc Auth(AuthRequest) returns (AuthReply) {} 22 | 23 | // Returns the currently used public key. 24 | rpc SigningKey(SigningKeyRequest) returns (SigningKeyReply) {} 25 | } 26 | 27 | message GetTokenRequest { 28 | // Target RPC endpoint. 29 | string target = 1; 30 | } 31 | 32 | message GetTokenReply { 33 | // JWT to use with target RPC. 34 | string session_jwt = 1; 35 | } 36 | 37 | service CredStore { 38 | // GetToken provides a JWT token for remote endpoint based on its DNS name. 39 | rpc GetToken(GetTokenRequest) returns (GetTokenReply) {} 40 | } 41 | -------------------------------------------------------------------------------- /server/auth_server.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package server 20 | 21 | import ( 22 | "crypto/ecdsa" 23 | "crypto/x509" 24 | "encoding/json" 25 | "fmt" 26 | 27 | "github.com/golang/glog" 28 | pb "github.com/google/credstore/api" 29 | "github.com/google/credstore/client" 30 | "github.com/google/credstore/config" 31 | "github.com/google/credstore/jwt" 32 | "golang.org/x/net/context" 33 | "google.golang.org/grpc" 34 | "google.golang.org/grpc/codes" 35 | jose "gopkg.in/square/go-jose.v2" 36 | ) 37 | 38 | // AuthServer implements CredStoreAuth service. 39 | type AuthServer struct { 40 | signingKey *ecdsa.PrivateKey 41 | signer jose.Signer 42 | config *config.Config 43 | } 44 | 45 | type authServerTokenType struct{} 46 | 47 | var authServerToken = authServerTokenType{} 48 | 49 | // NewAuthServer returns a new AuthServer. 50 | func NewAuthServer(signingKey *ecdsa.PrivateKey, config *config.Config) (*AuthServer, error) { 51 | signer, err := jose.NewSigner( 52 | jose.SigningKey{Algorithm: jose.ES384, Key: signingKey}, 53 | &jose.SignerOptions{ 54 | ExtraHeaders: map[jose.HeaderKey]interface{}{"typ": "JWT"}, 55 | }) 56 | if err != nil { 57 | return nil, fmt.Errorf("failed to create JWT signer: %v", err) 58 | } 59 | 60 | return &AuthServer{signingKey: signingKey, signer: signer, config: config}, nil 61 | } 62 | 63 | // Auth takes in a static jwt (bundled into the binary) and returns a session 64 | // jwt, useable for other RPCs with credstore. 65 | func (s AuthServer) Auth(ctx context.Context, req *pb.AuthRequest) (*pb.AuthReply, error) { 66 | tok := ctx.Value(authServerToken).(jwt.AppToken) 67 | client := tok.Client 68 | 69 | if !s.config.FindClient(client) { 70 | glog.Errorf("client %s is not authorized to access this server", client) 71 | return nil, grpc.Errorf(codes.PermissionDenied, "client %s is not authorized to access this server", client) 72 | } 73 | 74 | authToken, err := jwt.BuildAuthToken(client) 75 | if err != nil { 76 | glog.Errorf("failed to serialize JWT token: %v", err) 77 | return nil, grpc.Errorf(codes.Internal, "failed to serialize JWT token: %v", err) 78 | } 79 | object, err := s.signer.Sign(authToken) 80 | if err != nil { 81 | glog.Errorf("failed to sign JWT payload: %v", err) 82 | return nil, grpc.Errorf(codes.Internal, "failed to sign JWT payload: %v", err) 83 | } 84 | 85 | serialized, err := object.CompactSerialize() 86 | if err != nil { 87 | glog.Errorf("failed to serialize short-form token: %v", err) 88 | return nil, grpc.Errorf(codes.Internal, "failed to serialize short-form token: %v", err) 89 | } 90 | 91 | repl := &pb.AuthReply{AuthJwt: serialized} 92 | 93 | return repl, nil 94 | } 95 | 96 | // SigningKey returns the currently used public key. 97 | func (s AuthServer) SigningKey(context.Context, *pb.SigningKeyRequest) (*pb.SigningKeyReply, error) { 98 | pubkeyBytes, err := x509.MarshalPKIXPublicKey(s.signingKey.Public()) 99 | if err != nil { 100 | glog.Errorf("failed to marshal ec public key: %v", err) 101 | return nil, grpc.Errorf(codes.Internal, "failed to marshal ec public key: %v", err) 102 | } 103 | 104 | repl := &pb.SigningKeyReply{ 105 | SigningKey: pubkeyBytes, 106 | } 107 | 108 | return repl, nil 109 | } 110 | 111 | // AuthServerInterceptor build inerceptor that verifies access to auth handler. 112 | func AuthServerInterceptor() grpc.UnaryServerInterceptor { 113 | return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { 114 | _, ok := info.Server.(*AuthServer) 115 | if !ok { 116 | return handler(ctx, req) 117 | } 118 | 119 | jwtTokString := ctx.Value(client.TokenKey).([]byte) 120 | var jwtTok jwt.AppToken 121 | err := json.Unmarshal(jwtTokString, &jwtTok) 122 | if err != nil { 123 | glog.Errorf("cannot deserialize JWT token: %v", err) 124 | return nil, grpc.Errorf(codes.Unauthenticated, "cannot deserialize JWT token: %v", err) 125 | } 126 | 127 | if err := jwtTok.Verify(); err != nil { 128 | glog.Errorf("cannot verify JWT token: %v", err) 129 | return nil, grpc.Errorf(codes.Unauthenticated, "cannot verify JWT token: %v", err) 130 | } 131 | 132 | newCtx := context.WithValue(ctx, authServerToken, jwtTok) 133 | return handler(newCtx, req) 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /server/credstore_server.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 Google Inc. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package server 20 | 21 | import ( 22 | "crypto/ecdsa" 23 | "encoding/json" 24 | "fmt" 25 | 26 | "github.com/golang/glog" 27 | pb "github.com/google/credstore/api" 28 | "github.com/google/credstore/client" 29 | "github.com/google/credstore/config" 30 | "github.com/google/credstore/jwt" 31 | "golang.org/x/net/context" 32 | "google.golang.org/grpc" 33 | "google.golang.org/grpc/codes" 34 | jose "gopkg.in/square/go-jose.v2" 35 | ) 36 | 37 | // CredStoreServer implements CredStore service. 38 | type CredStoreServer struct { 39 | signingKey *ecdsa.PrivateKey 40 | signer jose.Signer 41 | config *config.Config 42 | } 43 | 44 | type credStoreServerTokenType struct{} 45 | 46 | var credStoreServerToken = credStoreServerTokenType{} 47 | 48 | // NewCredStoreServer returns a new CredStoreServer. 49 | func NewCredStoreServer(signingKey *ecdsa.PrivateKey, config *config.Config) (*CredStoreServer, error) { 50 | signer, err := jose.NewSigner( 51 | jose.SigningKey{Algorithm: jose.ES384, Key: signingKey}, 52 | &jose.SignerOptions{ 53 | ExtraHeaders: map[jose.HeaderKey]interface{}{"typ": "JWT"}, 54 | }) 55 | if err != nil { 56 | return nil, fmt.Errorf("failed to create JWT signer: %v", err) 57 | } 58 | 59 | return &CredStoreServer{signingKey: signingKey, signer: signer, config: config}, nil 60 | } 61 | 62 | // GetToken provides a JWT token for remote endpoint based on its DNS name. 63 | func (s CredStoreServer) GetToken(ctx context.Context, req *pb.GetTokenRequest) (*pb.GetTokenReply, error) { 64 | tok := ctx.Value(credStoreServerToken).(jwt.AuthToken) 65 | client := tok.Client 66 | 67 | if !s.config.FindClient(client) { 68 | glog.Errorf("client %s is not authorized to access this server", client) 69 | return nil, grpc.Errorf(codes.PermissionDenied, "client %s is not authorized to access this server", client) 70 | } 71 | 72 | scopeName := s.config.FindAuthorization(client, req.GetTarget()) 73 | if scopeName == "" { 74 | glog.Errorf("client %s doesn't have a scope for %s", client, req.GetTarget()) 75 | return nil, grpc.Errorf(codes.PermissionDenied, "client %s doesn't have a scope for %s", client, req.GetTarget()) 76 | } 77 | 78 | scope := s.config.FindScope(scopeName) 79 | if scope == nil { 80 | glog.Errorf("client %s requested scope %s for %s, but no such scope is available", client, scopeName, req.GetTarget()) 81 | return nil, grpc.Errorf(codes.Internal, "client %s requested scope %s for %s, but no such scope is available", client, scopeName, req.GetTarget()) 82 | } 83 | 84 | rpcToken, err := jwt.BuildRPCToken(client, scope.Service, scope.Method) 85 | if err != nil { 86 | glog.Errorf("failed to serialize JWT token: %v", err) 87 | return nil, grpc.Errorf(codes.Internal, "failed to serialize JWT token: %v", err) 88 | } 89 | object, err := s.signer.Sign(rpcToken) 90 | if err != nil { 91 | glog.Errorf("failed to sign JWT payload: %v", err) 92 | return nil, grpc.Errorf(codes.Internal, "failed to sign JWT payload: %v", err) 93 | } 94 | serialized, err := object.CompactSerialize() 95 | if err != nil { 96 | glog.Errorf("failed to serialize short-form token: %v", err) 97 | return nil, grpc.Errorf(codes.Internal, "failed to serialize short-form token: %v", err) 98 | } 99 | 100 | repl := &pb.GetTokenReply{SessionJwt: serialized} 101 | 102 | return repl, nil 103 | } 104 | 105 | // CredStoreServerInterceptor build inerceptor that verifies access to auth handler. 106 | func CredStoreServerInterceptor() grpc.UnaryServerInterceptor { 107 | return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { 108 | _, ok := info.Server.(*CredStoreServer) 109 | if !ok { 110 | return handler(ctx, req) 111 | } 112 | 113 | jwtTokString := ctx.Value(client.TokenKey).([]byte) 114 | var jwtTok jwt.AuthToken 115 | err := json.Unmarshal(jwtTokString, &jwtTok) 116 | if err != nil { 117 | glog.Errorf("cannot deserialize JWT token: %v", err) 118 | return nil, grpc.Errorf(codes.Unauthenticated, "cannot deserialize JWT token: %v", err) 119 | } 120 | 121 | if err := jwtTok.Verify(); err != nil { 122 | glog.Errorf("cannot verify JWT token: %v", err) 123 | return nil, grpc.Errorf(codes.Unauthenticated, "cannot verify JWT token: %v", err) 124 | } 125 | 126 | newCtx := context.WithValue(ctx, credStoreServerToken, jwtTok) 127 | return handler(newCtx, req) 128 | } 129 | } 130 | --------------------------------------------------------------------------------