-
Notifications
You must be signed in to change notification settings - Fork 9
/
fnapi.go
252 lines (202 loc) · 7.64 KB
/
fnapi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package fnapi
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"time"
"github.com/spf13/pflag"
spb "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/versions"
"namespacelabs.dev/go-ids"
)
var (
EndpointAddress = "https://api.namespacelabs.net"
AdminMode = false
ExchangeGithubToTenantToken = false
UserAgent = "ns/unknown"
)
func SetupFlags(flags *pflag.FlagSet) {
flags.StringVar(&EndpointAddress, "fnapi_endpoint", EndpointAddress, "The fnapi endpoint address.")
_ = flags.MarkHidden("fnapi_endpoint")
flags.BoolVar(&AdminMode, "fnapi_admin", AdminMode, "Whether to enable admin mode.")
_ = flags.MarkHidden("fnapi_admin")
}
func StaticEndpoint(endpoint string) func(context.Context, ResolvedToken) (string, error) {
return func(context.Context, ResolvedToken) (string, error) {
return endpoint, nil
}
}
// A nil handle indicates that the caller wants to discard the response.
func AnonymousCall(ctx context.Context, endpoint string, method string, req interface{}, handle func(io.Reader) error) error {
return Call[any]{
Method: method,
IssueBearerToken: nil, // Callers of this API do not assume that credentials are injected.
}.Do(ctx, req, StaticEndpoint(endpoint), handle)
}
func AuthenticatedCall(ctx context.Context, endpoint string, method string, req interface{}, handle func(io.Reader) error) error {
return Call[any]{
Method: method,
IssueBearerToken: IssueBearerToken,
}.Do(ctx, req, StaticEndpoint(endpoint), handle)
}
func IssueTenantTokenFromSession(ctx context.Context, sessionToken string, duration time.Duration) (string, error) {
req := IssueTenantTokenFromSessionRequest{
TokenDurationSecs: int64(duration.Seconds()),
}
var resp IssueTenantTokenFromSessionResponse
if err := (Call[IssueTenantTokenFromSessionRequest]{
Method: "nsl.signin.SigninService/IssueTenantTokenFromSession",
IssueBearerToken: func(ctx context.Context) (ResolvedToken, error) {
return ResolvedToken{BearerToken: sessionToken}, nil
},
ScrubRequest: func(req *IssueTenantTokenFromSessionRequest) {
if req.SessionToken != "" {
req.SessionToken = "scrubed"
}
},
}).Do(ctx, req, StaticEndpoint(EndpointAddress), DecodeJSONResponse(&resp)); err != nil {
return "", err
}
return resp.TenantToken, nil
}
type Call[RequestT any] struct {
Method string
IssueBearerToken func(context.Context) (ResolvedToken, error)
ScrubRequest func(*RequestT)
}
func DecodeJSONResponse(resp any) func(io.Reader) error {
return func(body io.Reader) error {
return json.NewDecoder(body).Decode(resp)
}
}
func AddNamespaceHeaders(ctx context.Context, headers *http.Header) {
headers.Add("NS-Internal-Version", fmt.Sprintf("%d", versions.Builtin().APIVersion))
headers.Add("User-Agent", UserAgent)
if AdminMode {
headers.Add("NS-API-Mode", "admin")
}
}
func (c Call[RequestT]) Do(ctx context.Context, request RequestT, resolveEndpoint func(context.Context, ResolvedToken) (string, error), handle func(io.Reader) error) error {
headers := http.Header{}
var resolvedToken ResolvedToken
if c.IssueBearerToken != nil {
tok, err := c.IssueBearerToken(ctx)
if err != nil {
return err
}
resolvedToken = tok
headers.Add("Authorization", "Bearer "+tok.BearerToken)
}
AddNamespaceHeaders(ctx, &headers)
reqBytes, err := json.Marshal(request)
if err != nil {
return fnerrors.InternalError("failed to marshal request: %w", err)
}
endpoint, err := resolveEndpoint(ctx, resolvedToken)
if err != nil {
return err
}
tid := ids.NewRandomBase32ID(4)
fmt.Fprintf(console.Debug(ctx), "[%s] RPC: %v (endpoint: %v)\n", tid, c.Method, endpoint)
reqDebugBytes := reqBytes
if c.ScrubRequest != nil {
c.ScrubRequest(&request)
reqDebugBytes, _ = json.Marshal(request)
}
fmt.Fprintf(console.Debug(ctx), "[%s] Body: %s\n", tid, reqDebugBytes)
t := time.Now()
url := endpoint + "/" + c.Method
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(reqBytes))
if err != nil {
return fnerrors.InternalError("failed to construct request: %w", err)
}
for k, v := range headers {
httpReq.Header[k] = append(httpReq.Header[k], v...)
}
client := &http.Client{
Transport: http.DefaultTransport,
}
response, err := client.Do(httpReq)
if err != nil {
return fnerrors.InvocationError("namespace api", "http call failed: %w", err)
}
defer response.Body.Close()
fmt.Fprintf(console.Debug(ctx), "[%s] RPC: %v: status %s took %v\n", tid, c.Method, response.Status, time.Since(t))
if response.StatusCode == http.StatusOK {
if handle == nil {
return nil
}
return handle(response.Body)
}
respBody, err := io.ReadAll(response.Body)
if err != nil {
return fnerrors.InvocationError("namespace api", "reading response body: %w", err)
}
st := &spb.Status{}
if err := json.Unmarshal(respBody, st); err == nil {
return handleGrpcStatus(url, st)
} else {
fmt.Fprintf(console.Debug(ctx), "did not receive an RPC status: %v\n", err)
}
fmt.Fprintf(console.Debug(ctx), "Error body response: %s\n", string(respBody))
if grpcDetails := response.Header[http.CanonicalHeaderKey("grpc-status-details-bin")]; len(grpcDetails) > 0 {
data, err := base64.RawStdEncoding.DecodeString(grpcDetails[0])
if err != nil {
return fnerrors.InternalError("failed to decode grpc details: %w", err)
}
if err := proto.Unmarshal(data, st); err != nil {
return fnerrors.InternalError("failed to unmarshal grpc details: %w", err)
}
return handleGrpcStatus(url, st)
}
grpcMessage := response.Header[http.CanonicalHeaderKey("grpc-message")]
grpcStatus := response.Header[http.CanonicalHeaderKey("grpc-status")]
if len(grpcMessage) > 0 && len(grpcStatus) > 0 {
intVar, err := strconv.Atoi(grpcStatus[0])
if err == nil {
st.Code = int32(intVar)
st.Message = grpcMessage[0]
return handleGrpcStatus(url, st)
}
}
switch response.StatusCode {
case http.StatusInternalServerError:
return fnerrors.InternalError("namespace api: internal server error: %s", string(respBody))
case http.StatusUnauthorized:
return fnerrors.ReauthError("%s requires authentication", url)
case http.StatusForbidden:
return fnerrors.PermissionDeniedError("%s denied access", url)
case http.StatusNotFound:
return fnerrors.InternalError("%s not found: %s", url, string(respBody))
default:
return fnerrors.InvocationError("namespace api", "unexpected %d error reaching %q: %s", response.StatusCode, url, response.Status)
}
}
func handleGrpcStatus(url string, st *spb.Status) error {
switch st.Code {
case int32(codes.Unauthenticated):
return fnerrors.ReauthError("%s requires authentication: %w", url, status.ErrorProto(st))
case int32(codes.PermissionDenied):
return fnerrors.PermissionDeniedError("%s denied access: %w", url, status.ErrorProto(st))
case int32(codes.FailedPrecondition):
// Failed precondition is not retryable so we should not suggest that it is transient (e.g. invocation error suggests this).
return fnerrors.New("failed to call %s: %w", url, status.ErrorProto(st))
case int32(codes.Internal):
return fnerrors.InternalError("failed to call %s: %w", url, status.ErrorProto(st))
default:
return fnerrors.InvocationError("namespace api", "failed to call %s: %w", url, status.ErrorProto(st))
}
}