Skip to content
This repository was archived by the owner on Sep 30, 2024. It is now read-only.

Commit 162d383

Browse files
arafatkatzeevict
andauthored
Backport 5ce2eea to 5.5.x (#64166)
This is a backport PR to add changes from https://github.com/sourcegraph/sourcegraph/pull/64116 to v5.5.x to main to create a release of the frontend. ## Test plan <!-- REQUIRED; info at https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles --> ## Changelog <!-- OPTIONAL; info at https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c --> --------- Co-authored-by: Vincent <[email protected]>
1 parent 8cf3916 commit 162d383

File tree

7 files changed

+605
-7
lines changed

7 files changed

+605
-7
lines changed

cmd/customer-2315/BUILD.bazel

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
2+
load("@rules_pkg//:pkg.bzl", "pkg_tar")
3+
load("@container_structure_test//:defs.bzl", "container_structure_test")
4+
load("//dev:oci_defs.bzl", "image_repository", "oci_image", "oci_push", "oci_tarball")
5+
6+
go_library(
7+
name = "customer-2315_lib",
8+
srcs = ["main.go"],
9+
importpath = "github.com/sourcegraph/sourcegraph/cmd/customer-2315",
10+
tags = [TAG_CODY_PRIME],
11+
visibility = ["//visibility:private"],
12+
deps = [
13+
"@com_github_google_uuid//:uuid",
14+
"@com_github_sourcegraph_log//:log",
15+
],
16+
)
17+
18+
go_binary(
19+
name = "customer-2315",
20+
embed = [":customer-2315_lib"],
21+
tags = [TAG_CODY_PRIME],
22+
visibility = ["//visibility:public"],
23+
)
24+
25+
pkg_tar(
26+
name = "tar_customer-2315",
27+
srcs = [":customer-2315"],
28+
)
29+
30+
oci_image(
31+
name = "image",
32+
base = "//wolfi-images/sourcegraph-base:base_image",
33+
entrypoint = [
34+
"/sbin/tini",
35+
"--",
36+
"/customer-2315",
37+
],
38+
tars = [":tar_customer-2315"],
39+
user = "sourcegraph",
40+
)
41+
42+
oci_tarball(
43+
name = "image_tarball",
44+
image = ":image",
45+
repo_tags = ["customer-2315:candidate"],
46+
)
47+
48+
container_structure_test(
49+
name = "image_test",
50+
timeout = "short",
51+
configs = ["image_test.yaml"],
52+
driver = "docker",
53+
image = ":image",
54+
tags = [
55+
"exclusive",
56+
"requires-network",
57+
TAG_CODY_PRIME,
58+
],
59+
)
60+
61+
oci_push(
62+
name = "candidate_push",
63+
image = ":image",
64+
repository = image_repository("customer-2315"),
65+
)

cmd/customer-2315/image_test.yaml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
schemaVersion: "2.0.0"
2+
3+
commandTests:
4+
- name: "not running as root"
5+
command: "/usr/bin/id"
6+
args:
7+
- -u
8+
excludedOutput: ["^0"]
9+
exitCode: 0
10+
- name: "validate /customer-2315 file exists and is executable"
11+
command: "test"
12+
args:
13+
- "-x"
14+
- "/customer-2315"
15+
exitCode: 0

cmd/customer-2315/main.go

Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
package main
2+
3+
import (
4+
"bufio"
5+
"bytes"
6+
"encoding/json"
7+
"fmt"
8+
"io"
9+
"net/http"
10+
"net/url"
11+
"os"
12+
"strings"
13+
"sync"
14+
"time"
15+
16+
"github.com/sourcegraph/log"
17+
18+
"github.com/google/uuid"
19+
)
20+
21+
type ProxyServer struct {
22+
accessToken string
23+
tokenMutex sync.RWMutex
24+
client *http.Client
25+
azureEndpoint *url.URL
26+
logger log.Logger
27+
}
28+
29+
func (ps *ProxyServer) readSecretFile(path string) (string, error) {
30+
data, err := os.ReadFile(path)
31+
if err != nil {
32+
return "", err
33+
}
34+
return strings.TrimSpace(string(data)), nil
35+
}
36+
37+
func (ps *ProxyServer) generateHeaders(bearerToken string) map[string]string {
38+
return map[string]string{
39+
"correlationId": uuid.New().String(),
40+
"dataClassification": "sensitive",
41+
"dataSource": "internet",
42+
"Authorization": "Bearer " + bearerToken,
43+
}
44+
}
45+
46+
func (ps *ProxyServer) updateAccessToken() {
47+
for {
48+
token, err := ps.getAccessToken()
49+
if err != nil {
50+
ps.logger.Fatal("Error getting access token: %v", log.Error(err))
51+
} else {
52+
ps.tokenMutex.Lock()
53+
ps.accessToken = token
54+
ps.tokenMutex.Unlock()
55+
ps.logger.Info("Access token updated")
56+
}
57+
time.Sleep(1 * time.Minute)
58+
}
59+
}
60+
61+
func (ps *ProxyServer) initializeAzureEndpoint() {
62+
var err error
63+
azure_endpoint, err := ps.readSecretFile("/run/secrets/azure_endpoint")
64+
if err != nil {
65+
ps.logger.Fatal("error reading OAUTH_URL: %v", log.Error(err))
66+
}
67+
ps.azureEndpoint, err = url.Parse(azure_endpoint)
68+
if err != nil {
69+
ps.logger.Fatal("Invalid AZURE_ENDPOINT: %v", log.Error(err))
70+
}
71+
}
72+
73+
func (ps *ProxyServer) initializeClient() {
74+
ps.client = &http.Client{
75+
Transport: &http.Transport{
76+
MaxIdleConns: 400,
77+
MaxIdleConnsPerHost: 400,
78+
IdleConnTimeout: 90 * time.Second,
79+
DisableKeepAlives: false,
80+
},
81+
Timeout: 30 * time.Second,
82+
}
83+
}
84+
85+
func (ps *ProxyServer) getAccessToken() (string, error) {
86+
url, err := ps.readSecretFile("/run/secrets/oauth_url")
87+
if err != nil {
88+
return "", fmt.Errorf("error reading OAUTH_URL: %v", err)
89+
}
90+
clientID, err := ps.readSecretFile("/run/secrets/client_id")
91+
if err != nil {
92+
return "", fmt.Errorf("error reading CLIENT_ID: %v", err)
93+
}
94+
clientSecret, err := ps.readSecretFile("/run/secrets/client_secret")
95+
if err != nil {
96+
return "", fmt.Errorf("error reading CLIENT_SECRET: %v", err)
97+
}
98+
99+
data := map[string]string{
100+
"client_id": clientID,
101+
"client_secret": clientSecret,
102+
"scope": "azureopenai-readwrite",
103+
"grant_type": "client_credentials",
104+
}
105+
106+
jsonData, err := json.Marshal(data)
107+
if err != nil {
108+
return "", fmt.Errorf("error marshalling JSON: %v", err)
109+
}
110+
111+
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
112+
if err != nil {
113+
return "", fmt.Errorf("error creating request: %v", err)
114+
}
115+
116+
req.Header.Set("Content-Type", "application/json")
117+
118+
resp, err := ps.client.Do(req)
119+
if err != nil {
120+
return "", fmt.Errorf("error making request: %v", err)
121+
}
122+
defer resp.Body.Close()
123+
124+
if resp.StatusCode != http.StatusOK {
125+
return "", fmt.Errorf("request failed with status: %v", resp.Status)
126+
}
127+
128+
var result map[string]interface{}
129+
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
130+
return "", fmt.Errorf("error decoding response: %v", err)
131+
}
132+
133+
token, ok := result["access_token"].(string)
134+
if !ok {
135+
return "", fmt.Errorf("access token not found in response")
136+
}
137+
138+
return token, nil
139+
}
140+
141+
func (ps *ProxyServer) handleProxy(w http.ResponseWriter, req *http.Request) {
142+
target := ps.azureEndpoint.ResolveReference(req.URL)
143+
// Create a proxy request
144+
proxyReq, err := http.NewRequest(req.Method, target.String(), req.Body)
145+
if err != nil {
146+
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
147+
return
148+
}
149+
150+
// Copy headers from the original request
151+
for header, values := range req.Header {
152+
for _, value := range values {
153+
proxyReq.Header.Add(header, value)
154+
}
155+
}
156+
157+
ps.tokenMutex.RLock()
158+
bearerToken := ps.accessToken
159+
ps.tokenMutex.RUnlock()
160+
// Add generated headers
161+
headers := ps.generateHeaders(bearerToken)
162+
for key, value := range headers {
163+
proxyReq.Header.Set(key, value)
164+
}
165+
proxyReq.Header.Set("Api-Key", bearerToken)
166+
167+
resp, err := ps.client.Do(proxyReq)
168+
if err != nil {
169+
http.Error(w, "Bad Gateway", http.StatusBadGateway)
170+
return
171+
}
172+
defer resp.Body.Close()
173+
174+
// Write the headers and status code from the response to the client
175+
for header, values := range resp.Header {
176+
for _, value := range values {
177+
w.Header().Add(header, value)
178+
}
179+
}
180+
w.WriteHeader(resp.StatusCode)
181+
182+
// Stream the response body to the client
183+
reader := bufio.NewReader(resp.Body)
184+
buf := make([]byte, 32*1024)
185+
for {
186+
n, err := reader.Read(buf)
187+
if err != nil && err != io.EOF {
188+
ps.logger.Error("Error reading response body: %v", log.Error(err))
189+
http.Error(w, "Error reading response from upstream server", http.StatusBadGateway)
190+
return
191+
}
192+
if n == 0 {
193+
break
194+
}
195+
if _, writeErr := w.Write(buf[:n]); writeErr != nil {
196+
ps.logger.Fatal("Error writing response: %v", log.Error(writeErr))
197+
break
198+
}
199+
if flusher, ok := w.(http.Flusher); ok {
200+
flusher.Flush()
201+
}
202+
}
203+
}
204+
205+
func main() {
206+
liblog := log.Init(log.Resource{
207+
Name: "Special Oauth Server",
208+
})
209+
defer liblog.Sync()
210+
211+
logger := log.Scoped("server")
212+
213+
ps := &ProxyServer{
214+
logger: logger,
215+
}
216+
ps.initializeClient()
217+
ps.initializeAzureEndpoint()
218+
go ps.updateAccessToken()
219+
http.HandleFunc("/", ps.handleProxy)
220+
logger.Info("HTTP Proxy server is running on port 8080")
221+
if err := http.ListenAndServe(":8080", nil); err != nil {
222+
logger.Fatal("Failed to start HTTP server: %v", log.Error(err))
223+
}
224+
}

cmd/customer-4512/BUILD.bazel

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
2+
load("@rules_pkg//:pkg.bzl", "pkg_tar")
3+
load("@container_structure_test//:defs.bzl", "container_structure_test")
4+
load("//dev:oci_defs.bzl", "image_repository", "oci_image", "oci_push", "oci_tarball")
5+
6+
go_library(
7+
name = "customer-4512_lib",
8+
srcs = ["main.go"],
9+
importpath = "github.com/sourcegraph/sourcegraph/cmd/customer-4512",
10+
tags = [TAG_CODY_PRIME],
11+
visibility = ["//visibility:private"],
12+
deps = ["@com_github_sourcegraph_log//:log"],
13+
)
14+
15+
go_binary(
16+
name = "customer-4512",
17+
embed = [":customer-4512_lib"],
18+
tags = [TAG_CODY_PRIME],
19+
visibility = ["//visibility:public"],
20+
)
21+
22+
pkg_tar(
23+
name = "tar_customer-4512",
24+
srcs = [":customer-4512"],
25+
)
26+
27+
oci_image(
28+
name = "image",
29+
base = "//wolfi-images/sourcegraph-base:base_image",
30+
entrypoint = [
31+
"/sbin/tini",
32+
"--",
33+
"/customer-4512",
34+
],
35+
tars = [":tar_customer-4512"],
36+
user = "sourcegraph",
37+
)
38+
39+
oci_tarball(
40+
name = "image_tarball",
41+
image = ":image",
42+
repo_tags = ["customer-4512:candidate"],
43+
)
44+
45+
container_structure_test(
46+
name = "image_test",
47+
timeout = "short",
48+
configs = ["image_test.yaml"],
49+
driver = "docker",
50+
image = ":image",
51+
tags = [
52+
"exclusive",
53+
"requires-network",
54+
TAG_CODY_PRIME,
55+
],
56+
)
57+
58+
oci_push(
59+
name = "candidate_push",
60+
image = ":image",
61+
repository = image_repository("customer-4512"),
62+
)

cmd/customer-4512/image_test.yaml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
schemaVersion: "2.0.0"
2+
3+
commandTests:
4+
- name: "not running as root"
5+
command: "/usr/bin/id"
6+
args:
7+
- -u
8+
excludedOutput: ["^0"]
9+
exitCode: 0
10+
- name: "validate /customer-4512 file exists and is executable"
11+
command: "test"
12+
args:
13+
- "-x"
14+
- "/customer-4512"
15+
exitCode: 0

0 commit comments

Comments
 (0)