1
// Copyright 2018 Google LLC
2
// Copyright Envoy Project Authors
3
// SPDX-License-Identifier: Apache-2.0
4

            
5
#include "source/common/jwt/check_audience.h"
6

            
7
#include "absl/strings/match.h"
8

            
9
namespace Envoy {
10
namespace JwtVerify {
11
namespace {
12

            
13
// HTTP Protocol scheme prefix in JWT aud claim.
14
constexpr absl::string_view HTTPSchemePrefix("http://");
15

            
16
// HTTPS Protocol scheme prefix in JWT aud claim.
17
constexpr absl::string_view HTTPSSchemePrefix("https://");
18

            
19
850
std::string sanitizeAudience(const std::string& aud) {
20
850
  if (aud.empty()) {
21
2
    return aud;
22
2
  }
23

            
24
848
  size_t beg_pos = 0;
25
848
  bool sanitized = false;
26
  // Point beg to first character after protocol scheme prefix in audience.
27
848
  if (absl::StartsWith(aud, HTTPSchemePrefix)) {
28
224
    beg_pos = HTTPSchemePrefix.size();
29
224
    sanitized = true;
30
624
  } else if (absl::StartsWith(aud, HTTPSSchemePrefix)) {
31
223
    beg_pos = HTTPSSchemePrefix.size();
32
223
    sanitized = true;
33
223
  }
34

            
35
  // Point end to trailing slash in aud.
36
848
  size_t end_pos = aud.length();
37
848
  if (aud[end_pos - 1] == '/') {
38
230
    --end_pos;
39
230
    sanitized = true;
40
230
  }
41
848
  if (sanitized) {
42
453
    return aud.substr(beg_pos, end_pos - beg_pos);
43
453
  }
44
395
  return aud;
45
848
}
46

            
47
} // namespace
48

            
49
449
CheckAudience::CheckAudience(const std::vector<std::string>& config_audiences) {
50
825
  for (const auto& aud : config_audiences) {
51
672
    config_audiences_.insert(sanitizeAudience(aud));
52
672
  }
53
449
}
54

            
55
248
bool CheckAudience::areAudiencesAllowed(const std::vector<std::string>& jwt_audiences) const {
56
248
  if (config_audiences_.empty()) {
57
71
    return true;
58
71
  }
59
179
  for (const auto& aud : jwt_audiences) {
60
178
    if (config_audiences_.find(sanitizeAudience(aud)) != config_audiences_.end()) {
61
165
      return true;
62
165
    }
63
178
  }
64
12
  return false;
65
177
}
66

            
67
} // namespace JwtVerify
68
} // namespace Envoy