-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
197 lines (176 loc) · 5.07 KB
/
api.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package auth
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"time"
"github.com/google/cel-go/cel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
authv1 "go.seankhliao.com/mono/auth/v1"
"go.seankhliao.com/mono/yhttp"
"google.golang.org/protobuf/types/known/timestamppb"
)
// SessionID is also the cookie Value
// has a prefix of:
// - moou_ for user tokens
// - moox_ for anonymous tokens
// - mooa_ for admin tokens
// UserId is identifies the user
// - > 0 for valid users
// - = 0 for anonymous users
// - < 0 for admin tokens
type tokenInfoContextKey struct{}
var TokenInfoContextKey = tokenInfoContextKey{}
func FromContext(ctx context.Context) *authv1.TokenInfo {
val := ctx.Value(TokenInfoContextKey)
info, ok := val.(*authv1.TokenInfo)
if !ok {
return nil
}
return info
}
var (
_ yhttp.Interceptor = (&App{}).AuthN
_ yhttp.Interceptor = (&App{}).AuthZ(AllowAnonymous)
)
// AuthN ensures there's always a valid session.
// The user may be anonymous (UserId == 0).
func (a *App) AuthN(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
var info *authv1.TokenInfo
a.o.Region(r.Context(), "authentication", func(ctx context.Context, span trace.Span) error {
// get current session token
cookie, err := r.Cookie(a.cookieName)
if err == nil {
a.store.RDo(ctx, func(s *authv1.Store) {
info = s.GetSessions()[cookie.Value]
})
// TODO: check for session expiry?
}
if info == nil {
span.SetAttributes(
attribute.Bool("session.new", true),
)
// start a new anonymous session
token := genToken("moox_")
info = authv1.TokenInfo_builder{
SessionId: &token,
Created: timestamppb.Now(),
}.Build()
a.store.Do(ctx, func(s *authv1.Store) {
s.GetSessions()[info.GetSessionId()] = info
})
// send it to the client
http.SetCookie(rw, &http.Cookie{
Name: a.cookieName,
Value: info.GetSessionId(),
Path: "/",
Domain: a.cookieDomain,
MaxAge: int(time.Hour.Seconds()),
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Partitioned: true,
})
}
span.SetAttributes(
attribute.Int64("user.id", info.GetUserId()),
attribute.String("session.id", info.GetSessionId()),
attribute.Float64("session.age.seconds", time.Since(info.GetCreated().AsTime()).Seconds()),
)
return nil
})
ctx := context.WithValue(r.Context(), TokenInfoContextKey, info)
r = r.WithContext(ctx)
next.ServeHTTP(rw, r)
})
}
var (
AllowAnonymous = MustAuthZPolicy(`user_id >= 0`)
AllowRegistered = MustAuthZPolicy(`user_id > 0`)
)
func MustAuthZPolicy(policy string) cel.Program {
prog, err := AuthZPolicy(policy)
if err != nil {
panic(err)
}
return prog
}
func AuthZPolicy(policy string) (cel.Program, error) {
var info *authv1.TokenInfo
env, err := cel.NewEnv(
cel.DeclareContextProto(info.ProtoReflect().Descriptor()),
)
if err != nil {
return nil, fmt.Errorf("prepare policy env: %w", err)
}
ast, iss := env.Compile(policy)
if iss.Err() != nil {
return nil, fmt.Errorf("compile policy: %w", err)
}
prog, err := env.Program(ast)
if err != nil {
return nil, fmt.Errorf("prepare policy program: %w", err)
}
return prog, nil
}
var errUnauthorized = errors.New("unauthorized")
func (a *App) AuthZ(policy cel.Program) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
err := a.o.Region(ctx, "authorization", func(ctx context.Context, span trace.Span) error {
info := FromContext(ctx)
act, err := cel.ContextProtoVars(info)
if err != nil {
return fmt.Errorf("prepare authz eval context: %w", err)
}
res, _, err := policy.ContextEval(ctx, act)
if err != nil {
return fmt.Errorf("evaluate policy: %w", err)
}
allow, ok := res.Value().(bool)
if !ok {
return fmt.Errorf("policy eval result type %T", res.Value())
}
span.SetAttributes(
attribute.Bool("auth.allow", allow),
)
if !allow {
return errUnauthorized
}
return nil
})
if errors.Is(err, errUnauthorized) {
q := make(url.Values)
if r.Host != a.host {
q.Set("return", (&url.URL{
Scheme: "https",
Host: r.Host,
Path: r.URL.Path,
RawQuery: r.URL.RawQuery,
}).String())
}
u := (&url.URL{
Scheme: "https",
Host: a.host,
Path: "/",
RawQuery: q.Encode(),
}).String()
http.Redirect(rw, r, u, http.StatusTemporaryRedirect)
a.mAuthz.Add(ctx, 1, metric.WithAttributes(attribute.String("result", "deny")))
return
} else if err != nil {
a.o.HTTPErr(ctx, "authorization error", err, rw, http.StatusInternalServerError)
a.mAuthz.Add(ctx, 1, metric.WithAttributes(attribute.String("result", "error")))
return
}
a.mAuthz.Add(ctx, 1, metric.WithAttributes(attribute.String("result", "allow")))
next.ServeHTTP(rw, r)
})
}
}