forked from DataDog/datadog-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
61 lines (50 loc) · 1.44 KB
/
util.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2018 Datadog, Inc.
package util
import (
"fmt"
"net/http"
"strings"
"github.com/DataDog/datadog-agent/pkg/api/security"
)
var token string
// SetAuthToken sets the session token
// Requires that the config has been set up before calling
func SetAuthToken() error {
// Noop if token is already set
if token != "" {
return nil
}
// token is only set once, no need to mutex protect
var err error
token, err = security.FetchAuthToken()
return err
}
// GetAuthToken gets the session token
func GetAuthToken() string {
return token
}
// Validate validates an http request
func Validate(w http.ResponseWriter, r *http.Request) (err error) {
auth := r.Header.Get("Authorization")
if auth == "" {
w.Header().Set("WWW-Authenticate", "Bearer realm=\"Datadog Agent\"")
err = fmt.Errorf("no session token provided")
http.Error(w, err.Error(), 401)
return
}
tok := strings.Split(auth, " ")
if tok[0] != "Bearer" {
w.Header().Set("WWW-Authenticate", "Bearer realm=\"Datadog Agent\"")
err = fmt.Errorf("Unsupported authorization scheme: %s", tok[0])
http.Error(w, err.Error(), 401)
return
}
if len(tok) < 2 || tok[1] != GetAuthToken() {
err = fmt.Errorf("invalid session token")
http.Error(w, err.Error(), 403)
}
return
}