Skip to content

Commit

Permalink
Migrate to the new Cloudflare endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
Caspervw committed Jul 29, 2024
1 parent ec34657 commit 09f9f73
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 50 deletions.
3 changes: 1 addition & 2 deletions cmd/signaling/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,11 @@ func main() {
}

credentialsClient := cloudflare.NewCredentialsClient(
os.Getenv("CLOUDFLARE_ZONE"),
os.Getenv("CLOUDFLARE_APP_ID"),
os.Getenv("CLOUDFLARE_AUTH_USER"),
os.Getenv("CLOUDFLARE_AUTH_KEY"),
2*time.Hour,
)

go credentialsClient.Run(ctx)

mux, cleanup := internal.Signaling(ctx, store, credentialsClient)
Expand Down
41 changes: 15 additions & 26 deletions internal/cloudflare/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,8 @@ import (
)

type CredentialsClient struct {
zone string
appID string
authUser string
authKey string
appID string
authKey string

lifetime time.Duration

Expand All @@ -28,12 +26,10 @@ type CredentialsClient struct {
HasFetchedFirstCredentials bool
}

func NewCredentialsClient(zone, appID, user, key string, lifetime time.Duration) *CredentialsClient {
func NewCredentialsClient(appID, key string, lifetime time.Duration) *CredentialsClient {
c := &CredentialsClient{
zone: zone,
appID: appID,
authUser: user,
authKey: key,
appID: appID,
authKey: key,

lifetime: lifetime,
}
Expand All @@ -43,11 +39,6 @@ func NewCredentialsClient(zone, appID, user, key string, lifetime time.Duration)
func (c *CredentialsClient) Run(ctx context.Context) {
logger := logging.GetLogger(ctx)

if c.zone == "" {
logger.Warn("no Cloudflare zone configured, not fetching credentials")
return
}

for ctx.Err() == nil {
start := time.Now()
logger.Info("refetching credentials")
Expand Down Expand Up @@ -87,22 +78,24 @@ func (c *CredentialsClient) GetCredentials(ctx context.Context) (*Credentials, e
}

func (c *CredentialsClient) fetchCredentials(ctx context.Context) (*Credentials, error) {
url := "https://api.cloudflare.com/client/v4/zones/" + c.zone + "/webrtc-turn/credential/" + c.appID
body := strings.NewReader(fmt.Sprintf(`{"lifetime":%d}`, c.lifetime/time.Second))
lifetime := c.lifetime / time.Second

url := "https://rtc.live.cloudflare.com/v1/turn/keys/" + c.appID + "/credentials/generate"
body := strings.NewReader(fmt.Sprintf(`{"ttl":%d}`, lifetime))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body)
if err != nil {
return nil, err
}
req.Header.Set("X-Auth-Email", c.authUser)
req.Header.Set("X-Auth-Key", c.authKey)
req.Header.Set("Authorization", "Bearer "+c.authKey)
req.Header.Set("Content-Type", "application/json")

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {

if resp.StatusCode/100 != 2 {
return nil, fmt.Errorf("unexpected error from Cloudflare: %s", resp.Status)
}

Expand All @@ -111,14 +104,10 @@ func (c *CredentialsClient) fetchCredentials(ctx context.Context) (*Credentials,
return nil, fmt.Errorf("failed to decode Cloudflare response: %w", err)
}

if !response.Success {
return nil, fmt.Errorf("cloudflare error: %v", response.Errors)
}

return &Credentials{
URL: response.URL(),
Username: response.Result.Userid,
Credential: response.Result.Credential,
Lifetime: response.Result.Lifetime,
Username: response.ICEServers.Userid,
Credential: response.ICEServers.Credential,
Lifetime: int(lifetime),
}, nil
}
27 changes: 11 additions & 16 deletions internal/cloudflare/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,21 @@ type Credentials struct {
}

type response struct {
Result struct {
Protocol string `json:"protocol"`
DNS struct {
Name string `json:"name"`
} `json:"dns"`
Lifetime int `json:"lifetime"`
Userid string `json:"userid"`
Credential string `json:"credential"`
} `json:"result"`
Success bool `json:"success"`
Errors []interface{} `json:"errors"`
ICEServers struct {
URLs []string `json:"urls"`
Userid string `json:"username"`
Credential string `json:"credential"`
} `json:"iceServers"`
}

// URL returns in the following format:
// turn:webrtc-turn.example.com:50000?transport=udp
func (r response) URL() string {
protocol := r.Result.Protocol
parts := strings.Split(protocol, "/")
if len(parts) != 2 {
parts = []string{"udp", "50000"}
for _, url := range r.ICEServers.URLs {
if strings.HasPrefix(url, "turn:") && strings.Contains(url, "?transport=udp") {
return url
}
}
return "turn:" + r.Result.DNS.Name + ":" + parts[1] + "?transport=" + parts[0]

return ""
}
10 changes: 4 additions & 6 deletions manifest/secrets.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ metadata:
type: Opaque
data:
DATABASE_URL: ENC[AES256_GCM,data:EzXrkgS8BELub+ABWGD9PM+JoyRnsMkRBMFkeXSbgh+xRzn7/KZmXHwRnWXw5LWnoQfXQQ9wTySo5nqNRQNCDTdbqgsyT+X0aOnUfq5YngC858i1,iv:1Hu/EXqU77qxW0Et2N73OzO6e0AO/nIcTf/YKile07s=,tag:zA70VRtIQjuAN39Ce5CrpQ==,type:str]
CLOUDFLARE_ZONE: ENC[AES256_GCM,data:s+XKPCMFclh12qLE9Xb3p0TV/OIbhDWbQLb78JaYe0DOdb2CrGVHVejdjlY=,iv:RcgN2FMYLgTTAeJiXf7jhYiqKETcM8Psif8X9m/qh1o=,tag:EfsjoqQc3PFLPQXl+PrsKg==,type:str]
CLOUDFLARE_APP_ID: ENC[AES256_GCM,data:B3yQojS4vYBPxjRnt0Jrl775t2PJ+epHuji3mqHYKNEmQfmEEds4eRFO2Iw=,iv:59MCC4HaPt+DvN4tWgMd81EQkM7Lpi+BvjH55fsM/GE=,tag:A4Uj5f8Euosn+paDcMpAdg==,type:str]
CLOUDFLARE_AUTH_USER: ENC[AES256_GCM,data:jBHAExEBiL6Y4dTb2uj1/1Rq1X0=,iv:R3B035o5YRJA90c8GfeOXIF//ZtmyrQ32r8mUESNkCE=,tag:IDVsB2OffaqTKBKNH0VW1g==,type:str]
CLOUDFLARE_AUTH_KEY: ENC[AES256_GCM,data:4G60R/hLtW+bL0bNatte/T05pzFVDy3ffA/okLB+rZ1eK6MVZiiAsTZjPiBOQo2zwzw/NMzjanc=,iv:FQsOY9TsrlHY/Ttxif99ZhWJgNEOEcvURqz0lCrbs/M=,tag:Xk+KYNT7bD6ks7EtH/Wi3A==,type:str]
CLOUDFLARE_APP_ID: ENC[AES256_GCM,data:IA+zEzgowAwq/+y5Sg28pl95sjiKYiuPj9niKpik4OWmYyuDJTpz8WuYdY8=,iv:89F0Uf3/H0rV157gfQcrNxWW68HKGXLSqGQDkZtPKx8=,tag:JMPJrtbwOJAl305+Ys1KIA==,type:str]
CLOUDFLARE_AUTH_KEY: ENC[AES256_GCM,data:EqSQbMPMyi0qs5dLThITL0kh7zmBTdUN3Xdwr2cUhF+uNJ1l0qhWEXKK6jvz8VhNIR+LfqGHAfugqvnsCtpRJ8CIHSayEoLc4t/NIW+Qbfn6UyiKr29CpA==,iv:7ajGSyPzd+iEmt3/8C5I572CnNgoJXlH7Y4gBOxk3oQ=,tag:FaNEAPiMLOfh8BSuEk2b8Q==,type:str]
METRICS_URL: ENC[AES256_GCM,data:s0JL5s6mT4seWFi7/4wu1itKS+NG3RbBKE7UEhmTAyI=,iv:/rcgu4RueZZGBhoKApe2OGQ3/XXFtD2h2e96OK6Q0co=,tag:T+pFAcWCpEoSYT8MTQmVwg==,type:str]
sops:
kms: []
Expand All @@ -19,8 +17,8 @@ sops:
azure_kv: []
hc_vault: []
age: []
lastmodified: "2024-07-29T13:46:38Z"
mac: ENC[AES256_GCM,data:1ryTK096p4YKMbNmLIrNEZboFtnzNIb0604DocYfL0hur1S1NGCo6sXCLuiQstRloGrU0IaSljDrjf0TrdDbombwUG3VXLSCHHicG3auaX8Q/rZuhNv4u2bg6mfPpGZV3CiJfe19Y4wb4LPaaFrOBLGEkHIX3QAecWnRgFL87bE=,iv:U5GZ+e2HAnpqEImhcNcUBvSHeyrnDBbr/UDFO/cckvY=,tag:hAsKgFeJjwADo4PBf4d8TA==,type:str]
lastmodified: "2024-07-29T14:25:15Z"
mac: ENC[AES256_GCM,data:Tau418hZWnctbIN3XMLw/G86xb1+79cK0GkxdirjZGTlDvLloUdICdBUisJpaGeM8br2sVnfegbh6fc1FrXqD4a1VpL9Kwn78/hqWenKI9+Ll+fzbSTi9IxDTag4ajwhVaATsRD6UF3ue2ev0jmdlVIQYzPij2eXOhjSbasQt6g=,iv:mPiv7CBE6VvfQbuF8nWX6s+3UFUYbdQj+EDyjg8hx60=,tag:hpUZykrRD0n1jYL6+3f6AA==,type:str]
pgp:
- created_at: "2024-03-26T10:58:44Z"
enc: |-
Expand Down

0 comments on commit 09f9f73

Please sign in to comment.