Debian Codegraph @

internal/authmodel/opa.go

raw symbols SCIP
1 package authmodel
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "net/url"
11 "strings"
12
13 "github.com/rs/zerolog"
14 "github.com/sassoftware/relic/v7/config"
15 "github.com/sassoftware/relic/v7/internal/httperror"
16 "github.com/sassoftware/relic/v7/internal/realip"
17 "github.com/sassoftware/relic/v7/internal/zhttp"
18 "github.com/sassoftware/relic/v7/lib/audit"
19 )
20
21 type PolicyAuth struct {
22 cli *http.Client
23 destURL string
24 usesDefault bool
25 }
26
27 func newPolicyAuthenticator(conf *config.Config) (*PolicyAuth, error) {
28 usesDefault := !strings.Contains(conf.Server.PolicyURL, "/v1/data")
29 return &PolicyAuth{
30 cli: new(http.Client),
31 destURL: conf.Server.PolicyURL,
32 usesDefault: usesDefault,
33 }, nil
34 }
35
36 func (a *PolicyAuth) Authenticate(req *http.Request) (UserInfo, error) {
37 // build input to policy
38 input := policyInput{
39 Path: req.URL.Path,
40 Query: req.URL.Query(),
41 Token: bearerToken(req),
42 }
43 if peerCerts, err := realip.PeerCertificates(req); err != nil {
44 return nil, err
45 } else if len(peerCerts) != 0 {
46 input.Fingerprint = fingerprint(peerCerts[0])
47 }
48 if input.Token == "" && input.Fingerprint == "" {
49 return nil, httperror.ErrTokenRequired
50 }
51 result, err := a.evaluate(req.Context(), input)
52 if err != nil {
53 return nil, err
54 }
55 // amend access log with authorization metadata
56 zhttp.AppendAccessLog(req, func(e *zerolog.Event) {
57 if result.Result.Subject != "" {
58 e.Str("user", result.Result.Subject)
59 }
60 e.Object("policy", result)
61 })
62 if !result.Result.Allow {
63 code := http.StatusForbidden
64 for _, e := range result.Result.Errors {
65 if should401[e] {
66 code = http.StatusUnauthorized
67 }
68 }
69 return nil, httperror.TokenAuthorizationError(code, result.Result.Errors)
70 }
71 return &PolicyInfo{
72 Subject: result.Result.Subject,
73 Roles: result.Result.Roles,
74 AllowedKeys: result.Result.AllowedKeys,
75 Claims: result.Result.Claims,
76 }, nil
77 }
78
79 func (a *PolicyAuth) evaluate(ctx context.Context, input policyInput) (*policyResponse, error) {
80 // marshal request
81 var blob []byte
82 var err error
83 if a.usesDefault {
84 // default decision takes just the input
85 blob, err = json.Marshal(input)
86 } else {
87 // posting to a specific package needs a structured request
88 blob, err = json.Marshal(policyRequest{Input: input})
89 }
90 if err != nil {
91 return nil, fmt.Errorf("marshaling decision: %w", err)
92 }
93 preq, err := http.NewRequestWithContext(ctx, http.MethodPost, a.destURL, bytes.NewReader(blob))
94 if err != nil {
95 return nil, fmt.Errorf("executing decision: %w", err)
96 }
97 preq.Header.Set("Content-Type", "application/json")
98 // execute decision
99 resp, err := a.cli.Do(preq)
100 if err != nil {
101 return nil, fmt.Errorf("executing decision: %w", err)
102 }
103 defer resp.Body.Close()
104 if resp.StatusCode >= 300 {
105 err = httperror.FromResponse(resp)
106 return nil, fmt.Errorf("executing decision: %w", err)
107 }
108 body, err := io.ReadAll(resp.Body)
109 if err != nil {
110 return nil, fmt.Errorf("parsing decision: %w", err)
111 }
112 decision := new(policyResponse)
113 if err := json.Unmarshal(body, decision); err != nil {
114 return nil, fmt.Errorf("parsing decision: %w", err)
115 }
116 return decision, nil
117 }
118
119 type PolicyInfo struct {
120 Subject string
121 Roles []string
122 AllowedKeys []string
123
124 Claims map[string]interface{}
125 }
126
127 // Allowed checks whether the named key is visible to the current user
128 func (i *PolicyInfo) Allowed(keyConf *config.KeyConfig) bool {
129 for _, allowedKey := range i.AllowedKeys {
130 if allowedKey == keyConf.Name() {
131 return true
132 }
133 }
134 for _, keyRole := range keyConf.Roles {
135 for _, allowedRole := range i.Roles {
136 if keyRole == allowedRole {
137 return true
138 }
139 }
140 }
141 return false
142 }
143
144 // AuditContext amends an audit record with the authenticated user's name
145 // and other relevant details
146 func (i *PolicyInfo) AuditContext(info *audit.Info) {
147 info.Attributes["client.sub"] = i.Subject
148 if v := i.Claims["iss"]; v != nil {
149 info.Attributes["client.iss"] = v
150 }
151 }
152
153 type policyRequest struct {
154 Input policyInput `json:"input"`
155 }
156
157 type policyInput struct {
158 Path string `json:"path"`
159 Query url.Values `json:"query"`
160 Token string `json:"token"`
161 Fingerprint string `json:"fingerprint"`
162 }
163
164 type policyResponse struct {
165 Result struct {
166 Allow bool `json:"allow"`
167 Subject string `json:"sub"`
168 Errors []string `json:"errors"`
169 Roles []string `json:"roles"`
170 AllowedKeys []string `json:"allowed_keys"`
171
172 Claims map[string]interface{} `json:"claims"`
173 } `json:"result"`
174 ID string `json:"decision_id"`
175 }
176
177 func (r *policyResponse) MarshalZerologObject(f *zerolog.Event) {
178 if r.Result.Allow {
179 f.Str("decision", "allowed")
180 } else {
181 f.Str("decision", "denied")
182 }
183 if len(r.Result.Errors) != 0 {
184 f.Strs("errors", r.Result.Errors)
185 }
186 if len(r.Result.Claims) != 0 {
187 f.Interface("claims", r.Result.Claims)
188 }
189 if r.ID != "" {
190 f.Str("id", r.ID)
191 }
192 }
193
194 func bearerToken(req *http.Request) string {
195 auth := req.Header.Get("Authorization")
196 const prefix = "Bearer "
197 if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
198 return ""
199 }
200 return auth[len(prefix):]
201 }
202
203 var should401 = map[string]bool{
204 "token is missing or not well-formed": true,
205 "token issuer is not in known_issuers": true,
206 "token is expired": true,
207 "token is not yet valid": true,
208 }