1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
13 "git.arvados.org/arvados.git/sdk/go/arvados"
14 "git.arvados.org/arvados.git/sdk/go/ctxlog"
18 maxPermCacheAge = time.Hour
19 minPermCacheAge = 5 * time.Minute
22 type permChecker interface {
23 SetToken(token string)
24 Check(ctx context.Context, uuid string) (bool, error)
27 func newPermChecker(ac arvados.Client) permChecker {
29 return &cachingPermChecker{
31 cache: make(map[string]cacheEnt),
36 type cacheEnt struct {
41 type cachingPermChecker struct {
43 cache map[string]cacheEnt
51 func (pc *cachingPermChecker) SetToken(token string) {
52 if pc.Client.AuthToken == token {
55 pc.Client.AuthToken = token
56 pc.cache = make(map[string]cacheEnt)
59 func (pc *cachingPermChecker) Check(ctx context.Context, uuid string) (bool, error) {
61 logger := ctxlog.FromContext(ctx).
62 WithField("token", pc.Client.AuthToken).
63 WithField("uuid", uuid)
66 if perm, ok := pc.cache[uuid]; ok && now.Sub(perm.Time) < maxPermCacheAge {
67 logger.WithField("allowed", perm.allowed).Debug("cache hit")
68 return perm.allowed, nil
70 var buf map[string]interface{}
71 path, err := pc.PathForUUID("get", uuid)
78 err = pc.RequestAndDecode(&buf, "GET", path, nil, url.Values{
79 "include_trash": {"true"},
80 "select": {`["uuid"]`},
86 } else if txErr, ok := err.(*arvados.TransactionError); ok && pc.isNotAllowed(txErr.StatusCode) {
89 logger.WithError(err).Error("lookup error")
92 logger.WithField("allowed", allowed).Debug("cache miss")
93 pc.cache[uuid] = cacheEnt{Time: now, allowed: allowed}
97 func (pc *cachingPermChecker) isNotAllowed(status int) bool {
99 case http.StatusForbidden, http.StatusUnauthorized, http.StatusNotFound:
106 func (pc *cachingPermChecker) tidy() {
107 if len(pc.cache) <= pc.maxCurrent*2 {
110 tooOld := time.Now().Add(-minPermCacheAge)
111 for uuid, t := range pc.cache {
112 if t.Before(tooOld) {
113 delete(pc.cache, uuid)
116 pc.maxCurrent = len(pc.cache)