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 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
80 err = pc.RequestAndDecodeContext(ctx, &buf, "GET", path, nil, url.Values{
81 "include_trash": {"true"},
82 "select": {`["uuid"]`},
88 } else if txErr, ok := err.(*arvados.TransactionError); ok && pc.isNotAllowed(txErr.StatusCode) {
91 logger.WithError(err).Error("lookup error")
94 logger.WithField("allowed", allowed).Debug("cache miss")
95 pc.cache[uuid] = cacheEnt{Time: now, allowed: allowed}
99 func (pc *cachingPermChecker) isNotAllowed(status int) bool {
101 case http.StatusForbidden, http.StatusUnauthorized, http.StatusNotFound:
108 func (pc *cachingPermChecker) tidy() {
109 if len(pc.cache) <= pc.maxCurrent*2 {
112 tooOld := time.Now().Add(-minPermCacheAge)
113 for uuid, t := range pc.cache {
114 if t.Before(tooOld) {
115 delete(pc.cache, uuid)
118 pc.maxCurrent = len(pc.cache)