Skip to content

Commit cf45639

Browse files
Add X-TENANT-ID header to REST api (#4)
1 parent 685a5d2 commit cf45639

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,5 @@ bazel-bin
1111
bazel-out
1212
bazel-testlogs
1313
bazel-zoekt
14+
15+
.DS_STORE

internal/tenant/rest_helper.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package tenant
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"net/http"
7+
8+
"github.com/sourcegraph/zoekt/internal/tenant/internal/tenanttype"
9+
"google.golang.org/grpc/codes"
10+
"google.golang.org/grpc/status"
11+
)
12+
13+
func InjectTenantFromHeader(ctx context.Context, header http.Header) (context.Context, error) {
14+
tenantID := header.Get("X-TENANT-ID") // TODO: we don't use headerKeyTenantID here so we don't need to change it and potentially break future grpc changes
15+
if tenantID != "" {
16+
tenant, err := tenanttype.Unmarshal(tenantID)
17+
if err != nil {
18+
return ctx, status.New(codes.InvalidArgument, fmt.Errorf("bad tenant value in header: %w", err).Error()).Err()
19+
}
20+
21+
return tenanttype.WithTenant(ctx, tenant), nil
22+
}
23+
return ctx, nil
24+
}

json/json.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"time"
88

99
"github.com/sourcegraph/zoekt"
10+
"github.com/sourcegraph/zoekt/internal/tenant"
1011
"github.com/sourcegraph/zoekt/query"
1112
)
1213

@@ -85,6 +86,12 @@ func (s *jsonSearcher) jsonSearch(w http.ResponseWriter, req *http.Request) {
8586
defer cancel()
8687
}
8788

89+
ctx, err = tenant.InjectTenantFromHeader(ctx, req.Header)
90+
if err != nil {
91+
jsonError(w, http.StatusBadRequest, err.Error())
92+
return
93+
}
94+
8895
if err := CalculateDefaultSearchLimits(ctx, q, s.Searcher, searchArgs.Opts); err != nil {
8996
jsonError(w, http.StatusInternalServerError, err.Error())
9097
return
@@ -146,6 +153,7 @@ func CalculateDefaultSearchLimits(ctx context.Context,
146153
}
147154

148155
func (s *jsonSearcher) jsonList(w http.ResponseWriter, req *http.Request) {
156+
ctx := req.Context()
149157
w.Header().Add("Content-Type", "application/json")
150158

151159
if req.Method != "POST" {
@@ -166,7 +174,13 @@ func (s *jsonSearcher) jsonList(w http.ResponseWriter, req *http.Request) {
166174
return
167175
}
168176

169-
listResult, err := s.Searcher.List(req.Context(), query, listArgs.Opts)
177+
ctx, err = tenant.InjectTenantFromHeader(ctx, req.Header)
178+
if err != nil {
179+
jsonError(w, http.StatusBadRequest, err.Error())
180+
return
181+
}
182+
183+
listResult, err := s.Searcher.List(ctx, query, listArgs.Opts)
170184
if err != nil {
171185
jsonError(w, http.StatusInternalServerError, err.Error())
172186
return

0 commit comments

Comments
 (0)